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 #include "opt_ddb.h"
39 #include "opt_ktrace.h"
40
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/capsicum.h>
44 #include <sys/counter.h>
45 #include <sys/filedesc.h>
46 #include <sys/fnv_hash.h>
47 #include <sys/kernel.h>
48 #include <sys/ktr.h>
49 #include <sys/lock.h>
50 #include <sys/malloc.h>
51 #include <sys/fcntl.h>
52 #include <sys/jail.h>
53 #include <sys/mount.h>
54 #include <sys/namei.h>
55 #include <sys/proc.h>
56 #include <sys/seqc.h>
57 #include <sys/sdt.h>
58 #include <sys/smr.h>
59 #include <sys/smp.h>
60 #include <sys/syscallsubr.h>
61 #include <sys/sysctl.h>
62 #include <sys/sysproto.h>
63 #include <sys/vnode.h>
64 #include <ck_queue.h>
65 #ifdef KTRACE
66 #include <sys/ktrace.h>
67 #endif
68 #ifdef INVARIANTS
69 #include <machine/_inttypes.h>
70 #endif
71
72 #include <security/audit/audit.h>
73 #include <security/mac/mac_framework.h>
74
75 #ifdef DDB
76 #include <ddb/ddb.h>
77 #endif
78
79 #include <vm/uma.h>
80
81 /*
82 * High level overview of name caching in the VFS layer.
83 *
84 * Originally caching was implemented as part of UFS, later extracted to allow
85 * use by other filesystems. A decision was made to make it optional and
86 * completely detached from the rest of the kernel, which comes with limitations
87 * outlined near the end of this comment block.
88 *
89 * This fundamental choice needs to be revisited. In the meantime, the current
90 * state is described below. Significance of all notable routines is explained
91 * in comments placed above their implementation. Scattered thoroughout the
92 * file are TODO comments indicating shortcomings which can be fixed without
93 * reworking everything (most of the fixes will likely be reusable). Various
94 * details are omitted from this explanation to not clutter the overview, they
95 * have to be checked by reading the code and associated commentary.
96 *
97 * Keep in mind that it's individual path components which are cached, not full
98 * paths. That is, for a fully cached path "foo/bar/baz" there are 3 entries,
99 * one for each name.
100 *
101 * I. Data organization
102 *
103 * Entries are described by "struct namecache" objects and stored in a hash
104 * table. See cache_get_hash for more information.
105 *
106 * "struct vnode" contains pointers to source entries (names which can be found
107 * when traversing through said vnode), destination entries (names of that
108 * vnode (see "Limitations" for a breakdown on the subject) and a pointer to
109 * the parent vnode.
110 *
111 * The (directory vnode; name) tuple reliably determines the target entry if
112 * it exists.
113 *
114 * Since there are no small locks at this time (all are 32 bytes in size on
115 * LP64), the code works around the problem by introducing lock arrays to
116 * protect hash buckets and vnode lists.
117 *
118 * II. Filesystem integration
119 *
120 * Filesystems participating in name caching do the following:
121 * - set vop_lookup routine to vfs_cache_lookup
122 * - set vop_cachedlookup to whatever can perform the lookup if the above fails
123 * - if they support lockless lookup (see below), vop_fplookup_vexec and
124 * vop_fplookup_symlink are set along with the MNTK_FPLOOKUP flag on the
125 * mount point
126 * - call cache_purge or cache_vop_* routines to eliminate stale entries as
127 * applicable
128 * - call cache_enter to add entries depending on the MAKEENTRY flag
129 *
130 * With the above in mind, there are 2 entry points when doing lookups:
131 * - ... -> namei -> cache_fplookup -- this is the default
132 * - ... -> VOP_LOOKUP -> vfs_cache_lookup -- normally only called by namei
133 * should the above fail
134 *
135 * Example code flow how an entry is added:
136 * ... -> namei -> cache_fplookup -> cache_fplookup_noentry -> VOP_LOOKUP ->
137 * vfs_cache_lookup -> VOP_CACHEDLOOKUP -> ufs_lookup_ino -> cache_enter
138 *
139 * III. Performance considerations
140 *
141 * For lockless case forward lookup avoids any writes to shared areas apart
142 * from the terminal path component. In other words non-modifying lookups of
143 * different files don't suffer any scalability problems in the namecache.
144 * Looking up the same file is limited by VFS and goes beyond the scope of this
145 * file.
146 *
147 * At least on amd64 the single-threaded bottleneck for long paths is hashing
148 * (see cache_get_hash). There are cases where the code issues acquire fence
149 * multiple times, they can be combined on architectures which suffer from it.
150 *
151 * For locked case each encountered vnode has to be referenced and locked in
152 * order to be handed out to the caller (normally that's namei). This
153 * introduces significant hit single-threaded and serialization multi-threaded.
154 *
155 * Reverse lookup (e.g., "getcwd") fully scales provided it is fully cached --
156 * avoids any writes to shared areas to any components.
157 *
158 * Unrelated insertions are partially serialized on updating the global entry
159 * counter and possibly serialized on colliding bucket or vnode locks.
160 *
161 * IV. Observability
162 *
163 * Note not everything has an explicit dtrace probe nor it should have, thus
164 * some of the one-liners below depend on implementation details.
165 *
166 * Examples:
167 *
168 * # Check what lookups failed to be handled in a lockless manner. Column 1 is
169 * # line number, column 2 is status code (see cache_fpl_status)
170 * dtrace -n 'vfs:fplookup:lookup:done { @[arg1, arg2] = count(); }'
171 *
172 * # Lengths of names added by binary name
173 * dtrace -n 'fbt::cache_enter_time:entry { @[execname] = quantize(args[2]->cn_namelen); }'
174 *
175 * # Same as above but only those which exceed 64 characters
176 * dtrace -n 'fbt::cache_enter_time:entry /args[2]->cn_namelen > 64/ { @[execname] = quantize(args[2]->cn_namelen); }'
177 *
178 * # Who is performing lookups with spurious slashes (e.g., "foo//bar") and what
179 * # path is it
180 * dtrace -n 'fbt::cache_fplookup_skip_slashes:entry { @[execname, stringof(args[0]->cnp->cn_pnbuf)] = count(); }'
181 *
182 * V. Limitations and implementation defects
183 *
184 * - since it is possible there is no entry for an open file, tools like
185 * "procstat" may fail to resolve fd -> vnode -> path to anything
186 * - even if a filesystem adds an entry, it may get purged (e.g., due to memory
187 * shortage) in which case the above problem applies
188 * - hardlinks are not tracked, thus if a vnode is reachable in more than one
189 * way, resolving a name may return a different path than the one used to
190 * open it (even if said path is still valid)
191 * - by default entries are not added for newly created files
192 * - adding an entry may need to evict negative entry first, which happens in 2
193 * distinct places (evicting on lookup, adding in a later VOP) making it
194 * impossible to simply reuse it
195 * - there is a simple scheme to evict negative entries as the cache is approaching
196 * its capacity, but it is very unclear if doing so is a good idea to begin with
197 * - vnodes are subject to being recycled even if target inode is left in memory,
198 * which loses the name cache entries when it perhaps should not. in case of tmpfs
199 * names get duplicated -- kept by filesystem itself and namecache separately
200 * - struct namecache has a fixed size and comes in 2 variants, often wasting space.
201 * now hard to replace with malloc due to dependence on SMR.
202 * - lack of better integration with the kernel also turns nullfs into a layered
203 * filesystem instead of something which can take advantage of caching
204 */
205
206 static SYSCTL_NODE(_vfs, OID_AUTO, cache, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
207 "Name cache");
208
209 SDT_PROVIDER_DECLARE(vfs);
210 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *", "char *",
211 "struct vnode *");
212 SDT_PROBE_DEFINE3(vfs, namecache, enter, duplicate, "struct vnode *", "char *",
213 "struct vnode *");
214 SDT_PROBE_DEFINE2(vfs, namecache, enter_negative, done, "struct vnode *",
215 "char *");
216 SDT_PROBE_DEFINE2(vfs, namecache, fullpath_smr, hit, "struct vnode *",
217 "const char *");
218 SDT_PROBE_DEFINE4(vfs, namecache, fullpath_smr, miss, "struct vnode *",
219 "struct namecache *", "int", "int");
220 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, entry, "struct vnode *");
221 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, hit, "struct vnode *",
222 "char *", "struct vnode *");
223 SDT_PROBE_DEFINE1(vfs, namecache, fullpath, miss, "struct vnode *");
224 SDT_PROBE_DEFINE3(vfs, namecache, fullpath, return, "int",
225 "struct vnode *", "char *");
226 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *", "char *",
227 "struct vnode *");
228 SDT_PROBE_DEFINE2(vfs, namecache, lookup, hit__negative,
229 "struct vnode *", "char *");
230 SDT_PROBE_DEFINE2(vfs, namecache, lookup, miss, "struct vnode *",
231 "char *");
232 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, hit, "struct vnode *",
233 "struct componentname *");
234 SDT_PROBE_DEFINE2(vfs, namecache, removecnp, miss, "struct vnode *",
235 "struct componentname *");
236 SDT_PROBE_DEFINE3(vfs, namecache, purge, done, "struct vnode *", "size_t", "size_t");
237 SDT_PROBE_DEFINE1(vfs, namecache, purge, batch, "int");
238 SDT_PROBE_DEFINE1(vfs, namecache, purge_negative, done, "struct vnode *");
239 SDT_PROBE_DEFINE1(vfs, namecache, purgevfs, done, "struct mount *");
240 SDT_PROBE_DEFINE3(vfs, namecache, zap, done, "struct vnode *", "char *",
241 "struct vnode *");
242 SDT_PROBE_DEFINE2(vfs, namecache, zap_negative, done, "struct vnode *",
243 "char *");
244 SDT_PROBE_DEFINE2(vfs, namecache, evict_negative, done, "struct vnode *",
245 "char *");
246 SDT_PROBE_DEFINE1(vfs, namecache, symlink, alloc__fail, "size_t");
247
248 SDT_PROBE_DEFINE3(vfs, fplookup, lookup, done, "struct nameidata", "int", "bool");
249 SDT_PROBE_DECLARE(vfs, namei, lookup, entry);
250 SDT_PROBE_DECLARE(vfs, namei, lookup, return);
251
252 static char __read_frequently cache_fast_lookup_enabled = true;
253
254 /*
255 * This structure describes the elements in the cache of recent
256 * names looked up by namei.
257 */
258 struct negstate {
259 u_char neg_flag;
260 u_char neg_hit;
261 };
262 _Static_assert(sizeof(struct negstate) <= sizeof(struct vnode *),
263 "the state must fit in a union with a pointer without growing it");
264
265 struct namecache {
266 LIST_ENTRY(namecache) nc_src; /* source vnode list */
267 TAILQ_ENTRY(namecache) nc_dst; /* destination vnode list */
268 CK_SLIST_ENTRY(namecache) nc_hash;/* hash chain */
269 struct vnode *nc_dvp; /* vnode of parent of name */
270 union {
271 struct vnode *nu_vp; /* vnode the name refers to */
272 struct negstate nu_neg;/* negative entry state */
273 } n_un;
274 u_char nc_flag; /* flag bits */
275 u_char nc_nlen; /* length of name */
276 char nc_name[0]; /* segment name + nul */
277 };
278
279 /*
280 * struct namecache_ts repeats struct namecache layout up to the
281 * nc_nlen member.
282 * struct namecache_ts is used in place of struct namecache when time(s) need
283 * to be stored. The nc_dotdottime field is used when a cache entry is mapping
284 * both a non-dotdot directory name plus dotdot for the directory's
285 * parent.
286 *
287 * See below for alignment requirement.
288 */
289 struct namecache_ts {
290 struct timespec nc_time; /* timespec provided by fs */
291 struct timespec nc_dotdottime; /* dotdot timespec provided by fs */
292 int nc_ticks; /* ticks value when entry was added */
293 int nc_pad;
294 struct namecache nc_nc;
295 };
296
297 TAILQ_HEAD(cache_freebatch, namecache);
298
299 /*
300 * At least mips n32 performs 64-bit accesses to timespec as found
301 * in namecache_ts and requires them to be aligned. Since others
302 * may be in the same spot suffer a little bit and enforce the
303 * alignment for everyone. Note this is a nop for 64-bit platforms.
304 */
305 #define CACHE_ZONE_ALIGNMENT UMA_ALIGNOF(time_t)
306
307 /*
308 * TODO: the initial value of CACHE_PATH_CUTOFF was inherited from the
309 * 4.4 BSD codebase. Later on struct namecache was tweaked to become
310 * smaller and the value was bumped to retain the total size, but it
311 * was never re-evaluated for suitability. A simple test counting
312 * lengths during package building shows that the value of 45 covers
313 * about 86% of all added entries, reaching 99% at 65.
314 *
315 * Regardless of the above, use of dedicated zones instead of malloc may be
316 * inducing additional waste. This may be hard to address as said zones are
317 * tied to VFS SMR. Even if retaining them, the current split should be
318 * re-evaluated.
319 */
320 #ifdef __LP64__
321 #define CACHE_PATH_CUTOFF 45
322 #define CACHE_LARGE_PAD 6
323 #else
324 #define CACHE_PATH_CUTOFF 41
325 #define CACHE_LARGE_PAD 2
326 #endif
327
328 #define CACHE_ZONE_SMALL_SIZE (offsetof(struct namecache, nc_name) + CACHE_PATH_CUTOFF + 1)
329 #define CACHE_ZONE_SMALL_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_SMALL_SIZE)
330 #define CACHE_ZONE_LARGE_SIZE (offsetof(struct namecache, nc_name) + NAME_MAX + 1 + CACHE_LARGE_PAD)
331 #define CACHE_ZONE_LARGE_TS_SIZE (offsetof(struct namecache_ts, nc_nc) + CACHE_ZONE_LARGE_SIZE)
332
333 _Static_assert((CACHE_ZONE_SMALL_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
334 _Static_assert((CACHE_ZONE_SMALL_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
335 _Static_assert((CACHE_ZONE_LARGE_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
336 _Static_assert((CACHE_ZONE_LARGE_TS_SIZE % (CACHE_ZONE_ALIGNMENT + 1)) == 0, "bad zone size");
337
338 #define nc_vp n_un.nu_vp
339 #define nc_neg n_un.nu_neg
340
341 /*
342 * Flags in namecache.nc_flag
343 */
344 #define NCF_WHITE 0x01
345 #define NCF_ISDOTDOT 0x02
346 #define NCF_TS 0x04
347 #define NCF_DTS 0x08
348 #define NCF_DVDROP 0x10
349 #define NCF_NEGATIVE 0x20
350 #define NCF_INVALID 0x40
351 #define NCF_WIP 0x80
352
353 /*
354 * Flags in negstate.neg_flag
355 */
356 #define NEG_HOT 0x01
357
358 static bool cache_neg_evict_cond(u_long lnumcache);
359
360 /*
361 * Mark an entry as invalid.
362 *
363 * This is called before it starts getting deconstructed.
364 */
365 static void
cache_ncp_invalidate(struct namecache * ncp)366 cache_ncp_invalidate(struct namecache *ncp)
367 {
368
369 KASSERT((ncp->nc_flag & NCF_INVALID) == 0,
370 ("%s: entry %p already invalid", __func__, ncp));
371 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_INVALID);
372 atomic_thread_fence_rel();
373 }
374
375 /*
376 * Check whether the entry can be safely used.
377 *
378 * All places which elide locks are supposed to call this after they are
379 * done with reading from an entry.
380 */
381 #define cache_ncp_canuse(ncp) ({ \
382 struct namecache *_ncp = (ncp); \
383 u_char _nc_flag; \
384 \
385 atomic_thread_fence_acq(); \
386 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
387 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP)) == 0); \
388 })
389
390 /*
391 * Like the above but also checks NCF_WHITE.
392 */
393 #define cache_fpl_neg_ncp_canuse(ncp) ({ \
394 struct namecache *_ncp = (ncp); \
395 u_char _nc_flag; \
396 \
397 atomic_thread_fence_acq(); \
398 _nc_flag = atomic_load_char(&_ncp->nc_flag); \
399 __predict_true((_nc_flag & (NCF_INVALID | NCF_WIP | NCF_WHITE)) == 0); \
400 })
401
402 VFS_SMR_DECLARE;
403
404 static SYSCTL_NODE(_vfs_cache, OID_AUTO, param, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
405 "Name cache parameters");
406
407 static u_int __read_mostly ncsize; /* the size as computed on creation or resizing */
408 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, size, CTLFLAG_RD, &ncsize, 0,
409 "Total namecache capacity");
410
411 u_int ncsizefactor = 2;
412 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, sizefactor, CTLFLAG_RW, &ncsizefactor, 0,
413 "Size factor for namecache");
414
415 static u_long __read_mostly ncnegfactor = 5; /* ratio of negative entries */
416 SYSCTL_ULONG(_vfs_cache_param, OID_AUTO, negfactor, CTLFLAG_RW, &ncnegfactor, 0,
417 "Ratio of negative namecache entries");
418
419 /*
420 * Negative entry % of namecache capacity above which automatic eviction is allowed.
421 *
422 * Check cache_neg_evict_cond for details.
423 */
424 static u_int ncnegminpct = 3;
425
426 static u_int __read_mostly neg_min; /* the above recomputed against ncsize */
427 SYSCTL_UINT(_vfs_cache_param, OID_AUTO, negmin, CTLFLAG_RD, &neg_min, 0,
428 "Negative entry count above which automatic eviction is allowed");
429
430 /*
431 * Structures associated with name caching.
432 */
433 #define NCHHASH(hash) \
434 (&nchashtbl[(hash) & nchash])
435 static __read_mostly CK_SLIST_HEAD(nchashhead, namecache) *nchashtbl;/* Hash Table */
436 static u_long __read_mostly nchash; /* size of hash table */
437 SYSCTL_ULONG(_debug, OID_AUTO, nchash, CTLFLAG_RD, &nchash, 0,
438 "Size of namecache hash table");
439 static u_long __exclusive_cache_line numneg; /* number of negative entries allocated */
440 static u_long __exclusive_cache_line numcache;/* number of cache entries allocated */
441
442 struct nchstats nchstats; /* cache effectiveness statistics */
443
444 static bool __read_mostly cache_rename_add = true;
445 SYSCTL_BOOL(_vfs, OID_AUTO, cache_rename_add, CTLFLAG_RW,
446 &cache_rename_add, 0, "");
447
448 static u_int __exclusive_cache_line neg_cycle;
449
450 #define ncneghash 3
451 #define numneglists (ncneghash + 1)
452
453 struct neglist {
454 struct mtx nl_evict_lock;
455 struct mtx nl_lock __aligned(CACHE_LINE_SIZE);
456 TAILQ_HEAD(, namecache) nl_list;
457 TAILQ_HEAD(, namecache) nl_hotlist;
458 u_long nl_hotnum;
459 } __aligned(CACHE_LINE_SIZE);
460
461 static struct neglist neglists[numneglists];
462
463 static inline struct neglist *
NCP2NEGLIST(struct namecache * ncp)464 NCP2NEGLIST(struct namecache *ncp)
465 {
466
467 return (&neglists[(((uintptr_t)(ncp) >> 8) & ncneghash)]);
468 }
469
470 static inline struct negstate *
NCP2NEGSTATE(struct namecache * ncp)471 NCP2NEGSTATE(struct namecache *ncp)
472 {
473
474 MPASS(atomic_load_char(&ncp->nc_flag) & NCF_NEGATIVE);
475 return (&ncp->nc_neg);
476 }
477
478 #define numbucketlocks (ncbuckethash + 1)
479 static u_int __read_mostly ncbuckethash;
480 static struct mtx_padalign __read_mostly *bucketlocks;
481 #define HASH2BUCKETLOCK(hash) \
482 ((struct mtx *)(&bucketlocks[((hash) & ncbuckethash)]))
483
484 #define numvnodelocks (ncvnodehash + 1)
485 static u_int __read_mostly ncvnodehash;
486 static struct mtx __read_mostly *vnodelocks;
487 static inline struct mtx *
VP2VNODELOCK(struct vnode * vp)488 VP2VNODELOCK(struct vnode *vp)
489 {
490
491 return (&vnodelocks[(((uintptr_t)(vp) >> 8) & ncvnodehash)]);
492 }
493
494 static void
cache_out_ts(struct namecache * ncp,struct timespec * tsp,int * ticksp)495 cache_out_ts(struct namecache *ncp, struct timespec *tsp, int *ticksp)
496 {
497 struct namecache_ts *ncp_ts;
498
499 KASSERT((ncp->nc_flag & NCF_TS) != 0 ||
500 (tsp == NULL && ticksp == NULL),
501 ("No NCF_TS"));
502
503 if (tsp == NULL)
504 return;
505
506 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
507 *tsp = ncp_ts->nc_time;
508 *ticksp = ncp_ts->nc_ticks;
509 }
510
511 #ifdef DEBUG_CACHE
512 static int __read_mostly doingcache = 1; /* 1 => enable the cache */
513 SYSCTL_INT(_debug, OID_AUTO, vfscache, CTLFLAG_RW, &doingcache, 0,
514 "VFS namecache enabled");
515 #endif
516
517 /* Export size information to userland */
518 SYSCTL_INT(_debug_sizeof, OID_AUTO, namecache, CTLFLAG_RD, SYSCTL_NULL_INT_PTR,
519 sizeof(struct namecache), "sizeof(struct namecache)");
520
521 /*
522 * The new name cache statistics
523 */
524 static SYSCTL_NODE(_vfs_cache, OID_AUTO, stats, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
525 "Name cache statistics");
526
527 #define STATNODE_ULONG(name, varname, descr) \
528 SYSCTL_ULONG(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
529 #define STATNODE_COUNTER(name, varname, descr) \
530 static COUNTER_U64_DEFINE_EARLY(varname); \
531 SYSCTL_COUNTER_U64(_vfs_cache_stats, OID_AUTO, name, CTLFLAG_RD, &varname, \
532 descr);
533 STATNODE_ULONG(neg, numneg, "Number of negative cache entries");
534 STATNODE_ULONG(count, numcache, "Number of cache entries");
535 STATNODE_COUNTER(heldvnodes, numcachehv, "Number of namecache entries with vnodes held");
536 STATNODE_COUNTER(drops, numdrops, "Number of dropped entries due to reaching the limit");
537 STATNODE_COUNTER(miss, nummiss, "Number of cache misses");
538 STATNODE_COUNTER(misszap, nummisszap, "Number of cache misses we do not want to cache");
539 STATNODE_COUNTER(poszaps, numposzaps,
540 "Number of cache hits (positive) we do not want to cache");
541 STATNODE_COUNTER(poshits, numposhits, "Number of cache hits (positive)");
542 STATNODE_COUNTER(negzaps, numnegzaps,
543 "Number of cache hits (negative) we do not want to cache");
544 STATNODE_COUNTER(neghits, numneghits, "Number of cache hits (negative)");
545 /* These count for vn_getcwd(), too. */
546 STATNODE_COUNTER(fullpathcalls, numfullpathcalls, "Number of fullpath search calls");
547 STATNODE_COUNTER(fullpathfail2, numfullpathfail2,
548 "Number of fullpath search errors (VOP_VPTOCNP failures)");
549 STATNODE_COUNTER(fullpathfail4, numfullpathfail4, "Number of fullpath search errors (ENOMEM)");
550 STATNODE_COUNTER(fullpathfound, numfullpathfound, "Number of successful fullpath calls");
551 STATNODE_COUNTER(symlinktoobig, symlinktoobig, "Number of times symlink did not fit the cache");
552
553 /*
554 * Debug or developer statistics.
555 */
556 static SYSCTL_NODE(_vfs_cache, OID_AUTO, debug, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
557 "Name cache debugging");
558 #define DEBUGNODE_ULONG(name, varname, descr) \
559 SYSCTL_ULONG(_vfs_cache_debug, OID_AUTO, name, CTLFLAG_RD, &varname, 0, descr);
560 static u_long zap_bucket_relock_success;
561 DEBUGNODE_ULONG(zap_bucket_relock_success, zap_bucket_relock_success,
562 "Number of successful removals after relocking");
563 static u_long zap_bucket_fail;
564 DEBUGNODE_ULONG(zap_bucket_fail, zap_bucket_fail, "");
565 static u_long zap_bucket_fail2;
566 DEBUGNODE_ULONG(zap_bucket_fail2, zap_bucket_fail2, "");
567 static u_long cache_lock_vnodes_cel_3_failures;
568 DEBUGNODE_ULONG(vnodes_cel_3_failures, cache_lock_vnodes_cel_3_failures,
569 "Number of times 3-way vnode locking failed");
570
571 static void cache_zap_locked(struct namecache *ncp);
572 static int vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
573 char **retbuf, size_t *buflen, size_t addend);
574 static int vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf,
575 char **retbuf, size_t *buflen);
576 static int vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf,
577 char **retbuf, size_t *len, size_t addend);
578
579 static MALLOC_DEFINE(M_VFSCACHE, "vfscache", "VFS name cache entries");
580
581 static inline void
cache_assert_vlp_locked(struct mtx * vlp)582 cache_assert_vlp_locked(struct mtx *vlp)
583 {
584
585 if (vlp != NULL)
586 mtx_assert(vlp, MA_OWNED);
587 }
588
589 static inline void
cache_assert_vnode_locked(struct vnode * vp)590 cache_assert_vnode_locked(struct vnode *vp)
591 {
592 struct mtx *vlp;
593
594 vlp = VP2VNODELOCK(vp);
595 cache_assert_vlp_locked(vlp);
596 }
597
598 /*
599 * Directory vnodes with entries are held for two reasons:
600 * 1. make them less of a target for reclamation in vnlru
601 * 2. suffer smaller performance penalty in locked lookup as requeieing is avoided
602 *
603 * It will be feasible to stop doing it altogether if all filesystems start
604 * supporting lockless lookup.
605 */
606 static void
cache_hold_vnode(struct vnode * vp)607 cache_hold_vnode(struct vnode *vp)
608 {
609
610 cache_assert_vnode_locked(vp);
611 VNPASS(LIST_EMPTY(&vp->v_cache_src), vp);
612 vhold(vp);
613 counter_u64_add(numcachehv, 1);
614 }
615
616 static void
cache_drop_vnode(struct vnode * vp)617 cache_drop_vnode(struct vnode *vp)
618 {
619
620 /*
621 * Called after all locks are dropped, meaning we can't assert
622 * on the state of v_cache_src.
623 */
624 vdrop(vp);
625 counter_u64_add(numcachehv, -1);
626 }
627
628 /*
629 * UMA zones.
630 */
631 static uma_zone_t __read_mostly cache_zone_small;
632 static uma_zone_t __read_mostly cache_zone_small_ts;
633 static uma_zone_t __read_mostly cache_zone_large;
634 static uma_zone_t __read_mostly cache_zone_large_ts;
635
636 char *
cache_symlink_alloc(size_t size,int flags)637 cache_symlink_alloc(size_t size, int flags)
638 {
639
640 if (size < CACHE_ZONE_SMALL_SIZE) {
641 return (uma_zalloc_smr(cache_zone_small, flags));
642 }
643 if (size < CACHE_ZONE_LARGE_SIZE) {
644 return (uma_zalloc_smr(cache_zone_large, flags));
645 }
646 counter_u64_add(symlinktoobig, 1);
647 SDT_PROBE1(vfs, namecache, symlink, alloc__fail, size);
648 return (NULL);
649 }
650
651 void
cache_symlink_free(char * string,size_t size)652 cache_symlink_free(char *string, size_t size)
653 {
654
655 MPASS(string != NULL);
656 KASSERT(size < CACHE_ZONE_LARGE_SIZE,
657 ("%s: size %zu too big", __func__, size));
658
659 if (size < CACHE_ZONE_SMALL_SIZE) {
660 uma_zfree_smr(cache_zone_small, string);
661 return;
662 }
663 if (size < CACHE_ZONE_LARGE_SIZE) {
664 uma_zfree_smr(cache_zone_large, string);
665 return;
666 }
667 __assert_unreachable();
668 }
669
670 static struct namecache *
cache_alloc_uma(int len,bool ts)671 cache_alloc_uma(int len, bool ts)
672 {
673 struct namecache_ts *ncp_ts;
674 struct namecache *ncp;
675
676 if (__predict_false(ts)) {
677 if (len <= CACHE_PATH_CUTOFF)
678 ncp_ts = uma_zalloc_smr(cache_zone_small_ts, M_WAITOK);
679 else
680 ncp_ts = uma_zalloc_smr(cache_zone_large_ts, M_WAITOK);
681 ncp = &ncp_ts->nc_nc;
682 } else {
683 if (len <= CACHE_PATH_CUTOFF)
684 ncp = uma_zalloc_smr(cache_zone_small, M_WAITOK);
685 else
686 ncp = uma_zalloc_smr(cache_zone_large, M_WAITOK);
687 }
688 return (ncp);
689 }
690
691 static void
cache_free_uma(struct namecache * ncp)692 cache_free_uma(struct namecache *ncp)
693 {
694 struct namecache_ts *ncp_ts;
695
696 if (__predict_false(ncp->nc_flag & NCF_TS)) {
697 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
698 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
699 uma_zfree_smr(cache_zone_small_ts, ncp_ts);
700 else
701 uma_zfree_smr(cache_zone_large_ts, ncp_ts);
702 } else {
703 if (ncp->nc_nlen <= CACHE_PATH_CUTOFF)
704 uma_zfree_smr(cache_zone_small, ncp);
705 else
706 uma_zfree_smr(cache_zone_large, ncp);
707 }
708 }
709
710 static struct namecache *
cache_alloc(int len,bool ts)711 cache_alloc(int len, bool ts)
712 {
713 u_long lnumcache;
714
715 /*
716 * Avoid blowout in namecache entries.
717 *
718 * Bugs:
719 * 1. filesystems may end up trying to add an already existing entry
720 * (for example this can happen after a cache miss during concurrent
721 * lookup), in which case we will call cache_neg_evict despite not
722 * adding anything.
723 * 2. the routine may fail to free anything and no provisions are made
724 * to make it try harder (see the inside for failure modes)
725 * 3. it only ever looks at negative entries.
726 */
727 lnumcache = atomic_fetchadd_long(&numcache, 1) + 1;
728 if (cache_neg_evict_cond(lnumcache)) {
729 lnumcache = atomic_load_long(&numcache);
730 }
731 if (__predict_false(lnumcache >= ncsize)) {
732 atomic_subtract_long(&numcache, 1);
733 counter_u64_add(numdrops, 1);
734 return (NULL);
735 }
736 return (cache_alloc_uma(len, ts));
737 }
738
739 static void
cache_free(struct namecache * ncp)740 cache_free(struct namecache *ncp)
741 {
742
743 MPASS(ncp != NULL);
744 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
745 cache_drop_vnode(ncp->nc_dvp);
746 }
747 cache_free_uma(ncp);
748 atomic_subtract_long(&numcache, 1);
749 }
750
751 static void
cache_free_batch(struct cache_freebatch * batch)752 cache_free_batch(struct cache_freebatch *batch)
753 {
754 struct namecache *ncp, *nnp;
755 int i;
756
757 i = 0;
758 if (TAILQ_EMPTY(batch))
759 goto out;
760 TAILQ_FOREACH_SAFE(ncp, batch, nc_dst, nnp) {
761 if ((ncp->nc_flag & NCF_DVDROP) != 0) {
762 cache_drop_vnode(ncp->nc_dvp);
763 }
764 cache_free_uma(ncp);
765 i++;
766 }
767 atomic_subtract_long(&numcache, i);
768 out:
769 SDT_PROBE1(vfs, namecache, purge, batch, i);
770 }
771
772 /*
773 * Hashing.
774 *
775 * The code was made to use FNV in 2001 and this choice needs to be revisited.
776 *
777 * Short summary of the difficulty:
778 * The longest name which can be inserted is NAME_MAX characters in length (or
779 * 255 at the time of writing this comment), while majority of names used in
780 * practice are significantly shorter (mostly below 10). More importantly
781 * majority of lookups performed find names are even shorter than that.
782 *
783 * This poses a problem where hashes which do better than FNV past word size
784 * (or so) tend to come with additional overhead when finalizing the result,
785 * making them noticeably slower for the most commonly used range.
786 *
787 * Consider a path like: /usr/obj/usr/src/sys/amd64/GENERIC/vnode_if.c
788 *
789 * When looking it up the most time consuming part by a large margin (at least
790 * on amd64) is hashing. Replacing FNV with something which pessimizes short
791 * input would make the slowest part stand out even more.
792 */
793
794 /*
795 * TODO: With the value stored we can do better than computing the hash based
796 * on the address.
797 */
798 static void
cache_prehash(struct vnode * vp)799 cache_prehash(struct vnode *vp)
800 {
801
802 vp->v_nchash = fnv_32_buf(&vp, sizeof(vp), FNV1_32_INIT);
803 }
804
805 static uint32_t
cache_get_hash(char * name,u_char len,struct vnode * dvp)806 cache_get_hash(char *name, u_char len, struct vnode *dvp)
807 {
808
809 return (fnv_32_buf(name, len, dvp->v_nchash));
810 }
811
812 static uint32_t
cache_get_hash_iter_start(struct vnode * dvp)813 cache_get_hash_iter_start(struct vnode *dvp)
814 {
815
816 return (dvp->v_nchash);
817 }
818
819 static uint32_t
cache_get_hash_iter(char c,uint32_t hash)820 cache_get_hash_iter(char c, uint32_t hash)
821 {
822
823 return (fnv_32_buf(&c, 1, hash));
824 }
825
826 static uint32_t
cache_get_hash_iter_finish(uint32_t hash)827 cache_get_hash_iter_finish(uint32_t hash)
828 {
829
830 return (hash);
831 }
832
833 static inline struct nchashhead *
NCP2BUCKET(struct namecache * ncp)834 NCP2BUCKET(struct namecache *ncp)
835 {
836 uint32_t hash;
837
838 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
839 return (NCHHASH(hash));
840 }
841
842 static inline struct mtx *
NCP2BUCKETLOCK(struct namecache * ncp)843 NCP2BUCKETLOCK(struct namecache *ncp)
844 {
845 uint32_t hash;
846
847 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen, ncp->nc_dvp);
848 return (HASH2BUCKETLOCK(hash));
849 }
850
851 #ifdef INVARIANTS
852 static void
cache_assert_bucket_locked(struct namecache * ncp)853 cache_assert_bucket_locked(struct namecache *ncp)
854 {
855 struct mtx *blp;
856
857 blp = NCP2BUCKETLOCK(ncp);
858 mtx_assert(blp, MA_OWNED);
859 }
860
861 static void
cache_assert_bucket_unlocked(struct namecache * ncp)862 cache_assert_bucket_unlocked(struct namecache *ncp)
863 {
864 struct mtx *blp;
865
866 blp = NCP2BUCKETLOCK(ncp);
867 mtx_assert(blp, MA_NOTOWNED);
868 }
869 #else
870 #define cache_assert_bucket_locked(x) do { } while (0)
871 #define cache_assert_bucket_unlocked(x) do { } while (0)
872 #endif
873
874 #define cache_sort_vnodes(x, y) _cache_sort_vnodes((void **)(x), (void **)(y))
875 static void
_cache_sort_vnodes(void ** p1,void ** p2)876 _cache_sort_vnodes(void **p1, void **p2)
877 {
878 void *tmp;
879
880 MPASS(*p1 != NULL || *p2 != NULL);
881
882 if (*p1 > *p2) {
883 tmp = *p2;
884 *p2 = *p1;
885 *p1 = tmp;
886 }
887 }
888
889 static void
cache_lock_all_buckets(void)890 cache_lock_all_buckets(void)
891 {
892 u_int i;
893
894 for (i = 0; i < numbucketlocks; i++)
895 mtx_lock(&bucketlocks[i]);
896 }
897
898 static void
cache_unlock_all_buckets(void)899 cache_unlock_all_buckets(void)
900 {
901 u_int i;
902
903 for (i = 0; i < numbucketlocks; i++)
904 mtx_unlock(&bucketlocks[i]);
905 }
906
907 static void
cache_lock_all_vnodes(void)908 cache_lock_all_vnodes(void)
909 {
910 u_int i;
911
912 for (i = 0; i < numvnodelocks; i++)
913 mtx_lock(&vnodelocks[i]);
914 }
915
916 static void
cache_unlock_all_vnodes(void)917 cache_unlock_all_vnodes(void)
918 {
919 u_int i;
920
921 for (i = 0; i < numvnodelocks; i++)
922 mtx_unlock(&vnodelocks[i]);
923 }
924
925 static int
cache_trylock_vnodes(struct mtx * vlp1,struct mtx * vlp2)926 cache_trylock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
927 {
928
929 cache_sort_vnodes(&vlp1, &vlp2);
930
931 if (vlp1 != NULL) {
932 if (!mtx_trylock(vlp1))
933 return (EAGAIN);
934 }
935 if (!mtx_trylock(vlp2)) {
936 if (vlp1 != NULL)
937 mtx_unlock(vlp1);
938 return (EAGAIN);
939 }
940
941 return (0);
942 }
943
944 static void
cache_lock_vnodes(struct mtx * vlp1,struct mtx * vlp2)945 cache_lock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
946 {
947
948 MPASS(vlp1 != NULL || vlp2 != NULL);
949 MPASS(vlp1 <= vlp2);
950
951 if (vlp1 != NULL)
952 mtx_lock(vlp1);
953 if (vlp2 != NULL)
954 mtx_lock(vlp2);
955 }
956
957 static void
cache_unlock_vnodes(struct mtx * vlp1,struct mtx * vlp2)958 cache_unlock_vnodes(struct mtx *vlp1, struct mtx *vlp2)
959 {
960
961 MPASS(vlp1 != NULL || vlp2 != NULL);
962
963 if (vlp1 != NULL)
964 mtx_unlock(vlp1);
965 if (vlp2 != NULL)
966 mtx_unlock(vlp2);
967 }
968
969 static int
sysctl_nchstats(SYSCTL_HANDLER_ARGS)970 sysctl_nchstats(SYSCTL_HANDLER_ARGS)
971 {
972 struct nchstats snap;
973
974 if (req->oldptr == NULL)
975 return (SYSCTL_OUT(req, 0, sizeof(snap)));
976
977 snap = nchstats;
978 snap.ncs_goodhits = counter_u64_fetch(numposhits);
979 snap.ncs_neghits = counter_u64_fetch(numneghits);
980 snap.ncs_badhits = counter_u64_fetch(numposzaps) +
981 counter_u64_fetch(numnegzaps);
982 snap.ncs_miss = counter_u64_fetch(nummisszap) +
983 counter_u64_fetch(nummiss);
984
985 return (SYSCTL_OUT(req, &snap, sizeof(snap)));
986 }
987 SYSCTL_PROC(_vfs_cache, OID_AUTO, nchstats, CTLTYPE_OPAQUE | CTLFLAG_RD |
988 CTLFLAG_MPSAFE, 0, 0, sysctl_nchstats, "LU",
989 "VFS cache effectiveness statistics");
990
991 static int
sysctl_hitpct(SYSCTL_HANDLER_ARGS)992 sysctl_hitpct(SYSCTL_HANDLER_ARGS)
993 {
994 long poshits, neghits, miss, total;
995 long pct;
996
997 poshits = counter_u64_fetch(numposhits);
998 neghits = counter_u64_fetch(numneghits);
999 miss = counter_u64_fetch(nummiss);
1000 total = poshits + neghits + miss;
1001
1002 pct = 0;
1003 if (total != 0)
1004 pct = ((poshits + neghits) * 100) / total;
1005 return (sysctl_handle_int(oidp, 0, pct, req));
1006 }
1007 SYSCTL_PROC(_vfs_cache_stats, OID_AUTO, hitpct,
1008 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RD, NULL, 0, sysctl_hitpct,
1009 "I", "Percentage of hits");
1010
1011 static void
cache_recalc_neg_min(void)1012 cache_recalc_neg_min(void)
1013 {
1014
1015 neg_min = (ncsize * ncnegminpct) / 100;
1016 }
1017
1018 static int
sysctl_negminpct(SYSCTL_HANDLER_ARGS)1019 sysctl_negminpct(SYSCTL_HANDLER_ARGS)
1020 {
1021 u_int val;
1022 int error;
1023
1024 val = ncnegminpct;
1025 error = sysctl_handle_int(oidp, &val, 0, req);
1026 if (error != 0 || req->newptr == NULL)
1027 return (error);
1028
1029 if (val == ncnegminpct)
1030 return (0);
1031 if (val < 0 || val > 99)
1032 return (EINVAL);
1033 ncnegminpct = val;
1034 cache_recalc_neg_min();
1035 return (0);
1036 }
1037
1038 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, negminpct,
1039 CTLTYPE_INT | CTLFLAG_MPSAFE | CTLFLAG_RW, NULL, 0, sysctl_negminpct,
1040 "I", "Negative entry \% of namecache capacity above which automatic eviction is allowed");
1041
1042 #ifdef DEBUG_CACHE
1043 /*
1044 * Grab an atomic snapshot of the name cache hash chain lengths
1045 */
1046 static SYSCTL_NODE(_debug, OID_AUTO, hashstat,
1047 CTLFLAG_RW | CTLFLAG_MPSAFE, NULL,
1048 "hash table stats");
1049
1050 static int
sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)1051 sysctl_debug_hashstat_rawnchash(SYSCTL_HANDLER_ARGS)
1052 {
1053 struct nchashhead *ncpp;
1054 struct namecache *ncp;
1055 int i, error, n_nchash, *cntbuf;
1056
1057 retry:
1058 n_nchash = nchash + 1; /* nchash is max index, not count */
1059 if (req->oldptr == NULL)
1060 return SYSCTL_OUT(req, 0, n_nchash * sizeof(int));
1061 cntbuf = malloc(n_nchash * sizeof(int), M_TEMP, M_ZERO | M_WAITOK);
1062 cache_lock_all_buckets();
1063 if (n_nchash != nchash + 1) {
1064 cache_unlock_all_buckets();
1065 free(cntbuf, M_TEMP);
1066 goto retry;
1067 }
1068 /* Scan hash tables counting entries */
1069 for (ncpp = nchashtbl, i = 0; i < n_nchash; ncpp++, i++)
1070 CK_SLIST_FOREACH(ncp, ncpp, nc_hash)
1071 cntbuf[i]++;
1072 cache_unlock_all_buckets();
1073 for (error = 0, i = 0; i < n_nchash; i++)
1074 if ((error = SYSCTL_OUT(req, &cntbuf[i], sizeof(int))) != 0)
1075 break;
1076 free(cntbuf, M_TEMP);
1077 return (error);
1078 }
1079 SYSCTL_PROC(_debug_hashstat, OID_AUTO, rawnchash, CTLTYPE_INT|CTLFLAG_RD|
1080 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_rawnchash, "S,int",
1081 "nchash chain lengths");
1082
1083 static int
sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)1084 sysctl_debug_hashstat_nchash(SYSCTL_HANDLER_ARGS)
1085 {
1086 int error;
1087 struct nchashhead *ncpp;
1088 struct namecache *ncp;
1089 int n_nchash;
1090 int count, maxlength, used, pct;
1091
1092 if (!req->oldptr)
1093 return SYSCTL_OUT(req, 0, 4 * sizeof(int));
1094
1095 cache_lock_all_buckets();
1096 n_nchash = nchash + 1; /* nchash is max index, not count */
1097 used = 0;
1098 maxlength = 0;
1099
1100 /* Scan hash tables for applicable entries */
1101 for (ncpp = nchashtbl; n_nchash > 0; n_nchash--, ncpp++) {
1102 count = 0;
1103 CK_SLIST_FOREACH(ncp, ncpp, nc_hash) {
1104 count++;
1105 }
1106 if (count)
1107 used++;
1108 if (maxlength < count)
1109 maxlength = count;
1110 }
1111 n_nchash = nchash + 1;
1112 cache_unlock_all_buckets();
1113 pct = (used * 100) / (n_nchash / 100);
1114 error = SYSCTL_OUT(req, &n_nchash, sizeof(n_nchash));
1115 if (error)
1116 return (error);
1117 error = SYSCTL_OUT(req, &used, sizeof(used));
1118 if (error)
1119 return (error);
1120 error = SYSCTL_OUT(req, &maxlength, sizeof(maxlength));
1121 if (error)
1122 return (error);
1123 error = SYSCTL_OUT(req, &pct, sizeof(pct));
1124 if (error)
1125 return (error);
1126 return (0);
1127 }
1128 SYSCTL_PROC(_debug_hashstat, OID_AUTO, nchash, CTLTYPE_INT|CTLFLAG_RD|
1129 CTLFLAG_MPSAFE, 0, 0, sysctl_debug_hashstat_nchash, "I",
1130 "nchash statistics (number of total/used buckets, maximum chain length, usage percentage)");
1131 #endif
1132
1133 /*
1134 * Negative entries management
1135 *
1136 * Various workloads create plenty of negative entries and barely use them
1137 * afterwards. Moreover malicious users can keep performing bogus lookups
1138 * adding even more entries. For example "make tinderbox" as of writing this
1139 * comment ends up with 2.6M namecache entries in total, 1.2M of which are
1140 * negative.
1141 *
1142 * As such, a rather aggressive eviction method is needed. The currently
1143 * employed method is a placeholder.
1144 *
1145 * Entries are split over numneglists separate lists, each of which is further
1146 * split into hot and cold entries. Entries get promoted after getting a hit.
1147 * Eviction happens on addition of new entry.
1148 */
1149 static SYSCTL_NODE(_vfs_cache, OID_AUTO, neg, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
1150 "Name cache negative entry statistics");
1151
1152 SYSCTL_ULONG(_vfs_cache_neg, OID_AUTO, count, CTLFLAG_RD, &numneg, 0,
1153 "Number of negative cache entries");
1154
1155 static COUNTER_U64_DEFINE_EARLY(neg_created);
1156 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, created, CTLFLAG_RD, &neg_created,
1157 "Number of created negative entries");
1158
1159 static COUNTER_U64_DEFINE_EARLY(neg_evicted);
1160 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evicted, CTLFLAG_RD, &neg_evicted,
1161 "Number of evicted negative entries");
1162
1163 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_empty);
1164 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_empty, CTLFLAG_RD,
1165 &neg_evict_skipped_empty,
1166 "Number of times evicting failed due to lack of entries");
1167
1168 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_missed);
1169 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_missed, CTLFLAG_RD,
1170 &neg_evict_skipped_missed,
1171 "Number of times evicting failed due to target entry disappearing");
1172
1173 static COUNTER_U64_DEFINE_EARLY(neg_evict_skipped_contended);
1174 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, evict_skipped_contended, CTLFLAG_RD,
1175 &neg_evict_skipped_contended,
1176 "Number of times evicting failed due to contention");
1177
1178 SYSCTL_COUNTER_U64(_vfs_cache_neg, OID_AUTO, hits, CTLFLAG_RD, &numneghits,
1179 "Number of cache hits (negative)");
1180
1181 static int
sysctl_neg_hot(SYSCTL_HANDLER_ARGS)1182 sysctl_neg_hot(SYSCTL_HANDLER_ARGS)
1183 {
1184 int i, out;
1185
1186 out = 0;
1187 for (i = 0; i < numneglists; i++)
1188 out += neglists[i].nl_hotnum;
1189
1190 return (SYSCTL_OUT(req, &out, sizeof(out)));
1191 }
1192 SYSCTL_PROC(_vfs_cache_neg, OID_AUTO, hot, CTLTYPE_INT | CTLFLAG_RD |
1193 CTLFLAG_MPSAFE, 0, 0, sysctl_neg_hot, "I",
1194 "Number of hot negative entries");
1195
1196 static void
cache_neg_init(struct namecache * ncp)1197 cache_neg_init(struct namecache *ncp)
1198 {
1199 struct negstate *ns;
1200
1201 ncp->nc_flag |= NCF_NEGATIVE;
1202 ns = NCP2NEGSTATE(ncp);
1203 ns->neg_flag = 0;
1204 ns->neg_hit = 0;
1205 counter_u64_add(neg_created, 1);
1206 }
1207
1208 #define CACHE_NEG_PROMOTION_THRESH 2
1209
1210 static bool
cache_neg_hit_prep(struct namecache * ncp)1211 cache_neg_hit_prep(struct namecache *ncp)
1212 {
1213 struct negstate *ns;
1214 u_char n;
1215
1216 ns = NCP2NEGSTATE(ncp);
1217 n = atomic_load_char(&ns->neg_hit);
1218 for (;;) {
1219 if (n >= CACHE_NEG_PROMOTION_THRESH)
1220 return (false);
1221 if (atomic_fcmpset_8(&ns->neg_hit, &n, n + 1))
1222 break;
1223 }
1224 return (n + 1 == CACHE_NEG_PROMOTION_THRESH);
1225 }
1226
1227 /*
1228 * Nothing to do here but it is provided for completeness as some
1229 * cache_neg_hit_prep callers may end up returning without even
1230 * trying to promote.
1231 */
1232 #define cache_neg_hit_abort(ncp) do { } while (0)
1233
1234 static void
cache_neg_hit_finish(struct namecache * ncp)1235 cache_neg_hit_finish(struct namecache *ncp)
1236 {
1237
1238 SDT_PROBE2(vfs, namecache, lookup, hit__negative, ncp->nc_dvp, ncp->nc_name);
1239 counter_u64_add(numneghits, 1);
1240 }
1241
1242 /*
1243 * Move a negative entry to the hot list.
1244 */
1245 static void
cache_neg_promote_locked(struct namecache * ncp)1246 cache_neg_promote_locked(struct namecache *ncp)
1247 {
1248 struct neglist *nl;
1249 struct negstate *ns;
1250
1251 ns = NCP2NEGSTATE(ncp);
1252 nl = NCP2NEGLIST(ncp);
1253 mtx_assert(&nl->nl_lock, MA_OWNED);
1254 if ((ns->neg_flag & NEG_HOT) == 0) {
1255 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1256 TAILQ_INSERT_TAIL(&nl->nl_hotlist, ncp, nc_dst);
1257 nl->nl_hotnum++;
1258 ns->neg_flag |= NEG_HOT;
1259 }
1260 }
1261
1262 /*
1263 * Move a hot negative entry to the cold list.
1264 */
1265 static void
cache_neg_demote_locked(struct namecache * ncp)1266 cache_neg_demote_locked(struct namecache *ncp)
1267 {
1268 struct neglist *nl;
1269 struct negstate *ns;
1270
1271 ns = NCP2NEGSTATE(ncp);
1272 nl = NCP2NEGLIST(ncp);
1273 mtx_assert(&nl->nl_lock, MA_OWNED);
1274 MPASS(ns->neg_flag & NEG_HOT);
1275 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1276 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1277 nl->nl_hotnum--;
1278 ns->neg_flag &= ~NEG_HOT;
1279 atomic_store_char(&ns->neg_hit, 0);
1280 }
1281
1282 /*
1283 * Move a negative entry to the hot list if it matches the lookup.
1284 *
1285 * We have to take locks, but they may be contended and in the worst
1286 * case we may need to go off CPU. We don't want to spin within the
1287 * smr section and we can't block with it. Exiting the section means
1288 * the found entry could have been evicted. We are going to look it
1289 * up again.
1290 */
1291 static bool
cache_neg_promote_cond(struct vnode * dvp,struct componentname * cnp,struct namecache * oncp,uint32_t hash)1292 cache_neg_promote_cond(struct vnode *dvp, struct componentname *cnp,
1293 struct namecache *oncp, uint32_t hash)
1294 {
1295 struct namecache *ncp;
1296 struct neglist *nl;
1297 u_char nc_flag;
1298
1299 nl = NCP2NEGLIST(oncp);
1300
1301 mtx_lock(&nl->nl_lock);
1302 /*
1303 * For hash iteration.
1304 */
1305 vfs_smr_enter();
1306
1307 /*
1308 * Avoid all surprises by only succeeding if we got the same entry and
1309 * bailing completely otherwise.
1310 * XXX There are no provisions to keep the vnode around, meaning we may
1311 * end up promoting a negative entry for a *new* vnode and returning
1312 * ENOENT on its account. This is the error we want to return anyway
1313 * and promotion is harmless.
1314 *
1315 * In particular at this point there can be a new ncp which matches the
1316 * search but hashes to a different neglist.
1317 */
1318 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1319 if (ncp == oncp)
1320 break;
1321 }
1322
1323 /*
1324 * No match to begin with.
1325 */
1326 if (__predict_false(ncp == NULL)) {
1327 goto out_abort;
1328 }
1329
1330 /*
1331 * The newly found entry may be something different...
1332 */
1333 if (!(ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1334 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))) {
1335 goto out_abort;
1336 }
1337
1338 /*
1339 * ... and not even negative.
1340 */
1341 nc_flag = atomic_load_char(&ncp->nc_flag);
1342 if ((nc_flag & NCF_NEGATIVE) == 0) {
1343 goto out_abort;
1344 }
1345
1346 if (!cache_ncp_canuse(ncp)) {
1347 goto out_abort;
1348 }
1349
1350 cache_neg_promote_locked(ncp);
1351 cache_neg_hit_finish(ncp);
1352 vfs_smr_exit();
1353 mtx_unlock(&nl->nl_lock);
1354 return (true);
1355 out_abort:
1356 vfs_smr_exit();
1357 mtx_unlock(&nl->nl_lock);
1358 return (false);
1359 }
1360
1361 static void
cache_neg_promote(struct namecache * ncp)1362 cache_neg_promote(struct namecache *ncp)
1363 {
1364 struct neglist *nl;
1365
1366 nl = NCP2NEGLIST(ncp);
1367 mtx_lock(&nl->nl_lock);
1368 cache_neg_promote_locked(ncp);
1369 mtx_unlock(&nl->nl_lock);
1370 }
1371
1372 static void
cache_neg_insert(struct namecache * ncp)1373 cache_neg_insert(struct namecache *ncp)
1374 {
1375 struct neglist *nl;
1376
1377 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1378 cache_assert_bucket_locked(ncp);
1379 nl = NCP2NEGLIST(ncp);
1380 mtx_lock(&nl->nl_lock);
1381 TAILQ_INSERT_TAIL(&nl->nl_list, ncp, nc_dst);
1382 mtx_unlock(&nl->nl_lock);
1383 atomic_add_long(&numneg, 1);
1384 }
1385
1386 static void
cache_neg_remove(struct namecache * ncp)1387 cache_neg_remove(struct namecache *ncp)
1388 {
1389 struct neglist *nl;
1390 struct negstate *ns;
1391
1392 cache_assert_bucket_locked(ncp);
1393 nl = NCP2NEGLIST(ncp);
1394 ns = NCP2NEGSTATE(ncp);
1395 mtx_lock(&nl->nl_lock);
1396 if ((ns->neg_flag & NEG_HOT) != 0) {
1397 TAILQ_REMOVE(&nl->nl_hotlist, ncp, nc_dst);
1398 nl->nl_hotnum--;
1399 } else {
1400 TAILQ_REMOVE(&nl->nl_list, ncp, nc_dst);
1401 }
1402 mtx_unlock(&nl->nl_lock);
1403 atomic_subtract_long(&numneg, 1);
1404 }
1405
1406 static struct neglist *
cache_neg_evict_select_list(void)1407 cache_neg_evict_select_list(void)
1408 {
1409 struct neglist *nl;
1410 u_int c;
1411
1412 c = atomic_fetchadd_int(&neg_cycle, 1) + 1;
1413 nl = &neglists[c % numneglists];
1414 if (!mtx_trylock(&nl->nl_evict_lock)) {
1415 counter_u64_add(neg_evict_skipped_contended, 1);
1416 return (NULL);
1417 }
1418 return (nl);
1419 }
1420
1421 static struct namecache *
cache_neg_evict_select_entry(struct neglist * nl)1422 cache_neg_evict_select_entry(struct neglist *nl)
1423 {
1424 struct namecache *ncp, *lncp;
1425 struct negstate *ns, *lns;
1426 int i;
1427
1428 mtx_assert(&nl->nl_evict_lock, MA_OWNED);
1429 mtx_assert(&nl->nl_lock, MA_OWNED);
1430 ncp = TAILQ_FIRST(&nl->nl_list);
1431 if (ncp == NULL)
1432 return (NULL);
1433 lncp = ncp;
1434 lns = NCP2NEGSTATE(lncp);
1435 for (i = 1; i < 4; i++) {
1436 ncp = TAILQ_NEXT(ncp, nc_dst);
1437 if (ncp == NULL)
1438 break;
1439 ns = NCP2NEGSTATE(ncp);
1440 if (ns->neg_hit < lns->neg_hit) {
1441 lncp = ncp;
1442 lns = ns;
1443 }
1444 }
1445 return (lncp);
1446 }
1447
1448 static bool
cache_neg_evict(void)1449 cache_neg_evict(void)
1450 {
1451 struct namecache *ncp, *ncp2;
1452 struct neglist *nl;
1453 struct vnode *dvp;
1454 struct mtx *dvlp;
1455 struct mtx *blp;
1456 uint32_t hash;
1457 u_char nlen;
1458 bool evicted;
1459
1460 nl = cache_neg_evict_select_list();
1461 if (nl == NULL) {
1462 return (false);
1463 }
1464
1465 mtx_lock(&nl->nl_lock);
1466 ncp = TAILQ_FIRST(&nl->nl_hotlist);
1467 if (ncp != NULL) {
1468 cache_neg_demote_locked(ncp);
1469 }
1470 ncp = cache_neg_evict_select_entry(nl);
1471 if (ncp == NULL) {
1472 counter_u64_add(neg_evict_skipped_empty, 1);
1473 mtx_unlock(&nl->nl_lock);
1474 mtx_unlock(&nl->nl_evict_lock);
1475 return (false);
1476 }
1477 nlen = ncp->nc_nlen;
1478 dvp = ncp->nc_dvp;
1479 hash = cache_get_hash(ncp->nc_name, nlen, dvp);
1480 dvlp = VP2VNODELOCK(dvp);
1481 blp = HASH2BUCKETLOCK(hash);
1482 mtx_unlock(&nl->nl_lock);
1483 mtx_unlock(&nl->nl_evict_lock);
1484 mtx_lock(dvlp);
1485 mtx_lock(blp);
1486 /*
1487 * Note that since all locks were dropped above, the entry may be
1488 * gone or reallocated to be something else.
1489 */
1490 CK_SLIST_FOREACH(ncp2, (NCHHASH(hash)), nc_hash) {
1491 if (ncp2 == ncp && ncp2->nc_dvp == dvp &&
1492 ncp2->nc_nlen == nlen && (ncp2->nc_flag & NCF_NEGATIVE) != 0)
1493 break;
1494 }
1495 if (ncp2 == NULL) {
1496 counter_u64_add(neg_evict_skipped_missed, 1);
1497 ncp = NULL;
1498 evicted = false;
1499 } else {
1500 MPASS(dvlp == VP2VNODELOCK(ncp->nc_dvp));
1501 MPASS(blp == NCP2BUCKETLOCK(ncp));
1502 SDT_PROBE2(vfs, namecache, evict_negative, done, ncp->nc_dvp,
1503 ncp->nc_name);
1504 cache_zap_locked(ncp);
1505 counter_u64_add(neg_evicted, 1);
1506 evicted = true;
1507 }
1508 mtx_unlock(blp);
1509 mtx_unlock(dvlp);
1510 if (ncp != NULL)
1511 cache_free(ncp);
1512 return (evicted);
1513 }
1514
1515 /*
1516 * Maybe evict a negative entry to create more room.
1517 *
1518 * The ncnegfactor parameter limits what fraction of the total count
1519 * can comprise of negative entries. However, if the cache is just
1520 * warming up this leads to excessive evictions. As such, ncnegminpct
1521 * (recomputed to neg_min) dictates whether the above should be
1522 * applied.
1523 *
1524 * Try evicting if the cache is close to full capacity regardless of
1525 * other considerations.
1526 */
1527 static bool
cache_neg_evict_cond(u_long lnumcache)1528 cache_neg_evict_cond(u_long lnumcache)
1529 {
1530 u_long lnumneg;
1531
1532 if (ncsize - 1000 < lnumcache)
1533 goto out_evict;
1534 lnumneg = atomic_load_long(&numneg);
1535 if (lnumneg < neg_min)
1536 return (false);
1537 if (lnumneg * ncnegfactor < lnumcache)
1538 return (false);
1539 out_evict:
1540 return (cache_neg_evict());
1541 }
1542
1543 /*
1544 * cache_zap_locked():
1545 *
1546 * Removes a namecache entry from cache, whether it contains an actual
1547 * pointer to a vnode or if it is just a negative cache entry.
1548 */
1549 static void
cache_zap_locked(struct namecache * ncp)1550 cache_zap_locked(struct namecache *ncp)
1551 {
1552 struct nchashhead *ncpp;
1553 struct vnode *dvp, *vp;
1554
1555 dvp = ncp->nc_dvp;
1556 vp = ncp->nc_vp;
1557
1558 if (!(ncp->nc_flag & NCF_NEGATIVE))
1559 cache_assert_vnode_locked(vp);
1560 cache_assert_vnode_locked(dvp);
1561 cache_assert_bucket_locked(ncp);
1562
1563 cache_ncp_invalidate(ncp);
1564
1565 ncpp = NCP2BUCKET(ncp);
1566 CK_SLIST_REMOVE(ncpp, ncp, namecache, nc_hash);
1567 if (!(ncp->nc_flag & NCF_NEGATIVE)) {
1568 SDT_PROBE3(vfs, namecache, zap, done, dvp, ncp->nc_name, vp);
1569 TAILQ_REMOVE(&vp->v_cache_dst, ncp, nc_dst);
1570 if (ncp == vp->v_cache_dd) {
1571 atomic_store_ptr(&vp->v_cache_dd, NULL);
1572 }
1573 } else {
1574 SDT_PROBE2(vfs, namecache, zap_negative, done, dvp, ncp->nc_name);
1575 cache_neg_remove(ncp);
1576 }
1577 if (ncp->nc_flag & NCF_ISDOTDOT) {
1578 if (ncp == dvp->v_cache_dd) {
1579 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1580 }
1581 } else {
1582 LIST_REMOVE(ncp, nc_src);
1583 if (LIST_EMPTY(&dvp->v_cache_src)) {
1584 ncp->nc_flag |= NCF_DVDROP;
1585 }
1586 }
1587 }
1588
1589 static void
cache_zap_negative_locked_vnode_kl(struct namecache * ncp,struct vnode * vp)1590 cache_zap_negative_locked_vnode_kl(struct namecache *ncp, struct vnode *vp)
1591 {
1592 struct mtx *blp;
1593
1594 MPASS(ncp->nc_dvp == vp);
1595 MPASS(ncp->nc_flag & NCF_NEGATIVE);
1596 cache_assert_vnode_locked(vp);
1597
1598 blp = NCP2BUCKETLOCK(ncp);
1599 mtx_lock(blp);
1600 cache_zap_locked(ncp);
1601 mtx_unlock(blp);
1602 }
1603
1604 static bool
cache_zap_locked_vnode_kl2(struct namecache * ncp,struct vnode * vp,struct mtx ** vlpp)1605 cache_zap_locked_vnode_kl2(struct namecache *ncp, struct vnode *vp,
1606 struct mtx **vlpp)
1607 {
1608 struct mtx *pvlp, *vlp1, *vlp2, *to_unlock;
1609 struct mtx *blp;
1610
1611 MPASS(vp == ncp->nc_dvp || vp == ncp->nc_vp);
1612 cache_assert_vnode_locked(vp);
1613
1614 if (ncp->nc_flag & NCF_NEGATIVE) {
1615 if (*vlpp != NULL) {
1616 mtx_unlock(*vlpp);
1617 *vlpp = NULL;
1618 }
1619 cache_zap_negative_locked_vnode_kl(ncp, vp);
1620 return (true);
1621 }
1622
1623 pvlp = VP2VNODELOCK(vp);
1624 blp = NCP2BUCKETLOCK(ncp);
1625 vlp1 = VP2VNODELOCK(ncp->nc_dvp);
1626 vlp2 = VP2VNODELOCK(ncp->nc_vp);
1627
1628 if (*vlpp == vlp1 || *vlpp == vlp2) {
1629 to_unlock = *vlpp;
1630 *vlpp = NULL;
1631 } else {
1632 if (*vlpp != NULL) {
1633 mtx_unlock(*vlpp);
1634 *vlpp = NULL;
1635 }
1636 cache_sort_vnodes(&vlp1, &vlp2);
1637 if (vlp1 == pvlp) {
1638 mtx_lock(vlp2);
1639 to_unlock = vlp2;
1640 } else {
1641 if (!mtx_trylock(vlp1))
1642 goto out_relock;
1643 to_unlock = vlp1;
1644 }
1645 }
1646 mtx_lock(blp);
1647 cache_zap_locked(ncp);
1648 mtx_unlock(blp);
1649 if (to_unlock != NULL)
1650 mtx_unlock(to_unlock);
1651 return (true);
1652
1653 out_relock:
1654 mtx_unlock(vlp2);
1655 mtx_lock(vlp1);
1656 mtx_lock(vlp2);
1657 MPASS(*vlpp == NULL);
1658 *vlpp = vlp1;
1659 return (false);
1660 }
1661
1662 /*
1663 * If trylocking failed we can get here. We know enough to take all needed locks
1664 * in the right order and re-lookup the entry.
1665 */
1666 static int
cache_zap_unlocked_bucket(struct namecache * ncp,struct componentname * cnp,struct vnode * dvp,struct mtx * dvlp,struct mtx * vlp,uint32_t hash,struct mtx * blp)1667 cache_zap_unlocked_bucket(struct namecache *ncp, struct componentname *cnp,
1668 struct vnode *dvp, struct mtx *dvlp, struct mtx *vlp, uint32_t hash,
1669 struct mtx *blp)
1670 {
1671 struct namecache *rncp;
1672 struct mtx *rvlp;
1673
1674 cache_assert_bucket_unlocked(ncp);
1675
1676 cache_sort_vnodes(&dvlp, &vlp);
1677 cache_lock_vnodes(dvlp, vlp);
1678 mtx_lock(blp);
1679 CK_SLIST_FOREACH(rncp, (NCHHASH(hash)), nc_hash) {
1680 if (rncp == ncp && rncp->nc_dvp == dvp &&
1681 rncp->nc_nlen == cnp->cn_namelen &&
1682 !bcmp(rncp->nc_name, cnp->cn_nameptr, rncp->nc_nlen))
1683 break;
1684 }
1685
1686 if (rncp == NULL)
1687 goto out_mismatch;
1688
1689 if (!(ncp->nc_flag & NCF_NEGATIVE))
1690 rvlp = VP2VNODELOCK(rncp->nc_vp);
1691 else
1692 rvlp = NULL;
1693 if (rvlp != vlp)
1694 goto out_mismatch;
1695
1696 cache_zap_locked(rncp);
1697 mtx_unlock(blp);
1698 cache_unlock_vnodes(dvlp, vlp);
1699 atomic_add_long(&zap_bucket_relock_success, 1);
1700 return (0);
1701
1702 out_mismatch:
1703 mtx_unlock(blp);
1704 cache_unlock_vnodes(dvlp, vlp);
1705 return (EAGAIN);
1706 }
1707
1708 static int __noinline
cache_zap_locked_bucket(struct namecache * ncp,struct componentname * cnp,uint32_t hash,struct mtx * blp)1709 cache_zap_locked_bucket(struct namecache *ncp, struct componentname *cnp,
1710 uint32_t hash, struct mtx *blp)
1711 {
1712 struct mtx *dvlp, *vlp;
1713 struct vnode *dvp;
1714
1715 cache_assert_bucket_locked(ncp);
1716
1717 dvlp = VP2VNODELOCK(ncp->nc_dvp);
1718 vlp = NULL;
1719 if (!(ncp->nc_flag & NCF_NEGATIVE))
1720 vlp = VP2VNODELOCK(ncp->nc_vp);
1721 if (cache_trylock_vnodes(dvlp, vlp) == 0) {
1722 cache_zap_locked(ncp);
1723 mtx_unlock(blp);
1724 cache_unlock_vnodes(dvlp, vlp);
1725 return (0);
1726 }
1727
1728 dvp = ncp->nc_dvp;
1729 mtx_unlock(blp);
1730 return (cache_zap_unlocked_bucket(ncp, cnp, dvp, dvlp, vlp, hash, blp));
1731 }
1732
1733 static __noinline int
cache_remove_cnp(struct vnode * dvp,struct componentname * cnp)1734 cache_remove_cnp(struct vnode *dvp, struct componentname *cnp)
1735 {
1736 struct namecache *ncp;
1737 struct mtx *blp;
1738 struct mtx *dvlp, *dvlp2;
1739 uint32_t hash;
1740 int error;
1741
1742 if (cnp->cn_namelen == 2 &&
1743 cnp->cn_nameptr[0] == '.' && cnp->cn_nameptr[1] == '.') {
1744 dvlp = VP2VNODELOCK(dvp);
1745 dvlp2 = NULL;
1746 mtx_lock(dvlp);
1747 retry_dotdot:
1748 ncp = dvp->v_cache_dd;
1749 if (ncp == NULL) {
1750 mtx_unlock(dvlp);
1751 if (dvlp2 != NULL)
1752 mtx_unlock(dvlp2);
1753 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1754 return (0);
1755 }
1756 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1757 if (!cache_zap_locked_vnode_kl2(ncp, dvp, &dvlp2))
1758 goto retry_dotdot;
1759 MPASS(dvp->v_cache_dd == NULL);
1760 mtx_unlock(dvlp);
1761 if (dvlp2 != NULL)
1762 mtx_unlock(dvlp2);
1763 cache_free(ncp);
1764 } else {
1765 atomic_store_ptr(&dvp->v_cache_dd, NULL);
1766 mtx_unlock(dvlp);
1767 if (dvlp2 != NULL)
1768 mtx_unlock(dvlp2);
1769 }
1770 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1771 return (1);
1772 }
1773
1774 /*
1775 * XXX note that access here is completely unlocked with no provisions
1776 * to keep the hash allocated. If one is sufficiently unlucky a
1777 * parallel cache resize can reallocate the hash, unmap backing pages
1778 * and cause the empty check below to fault.
1779 *
1780 * Fixing this has epsilon priority, but can be done with no overhead
1781 * for this codepath with sufficient effort.
1782 */
1783 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1784 blp = HASH2BUCKETLOCK(hash);
1785 retry:
1786 if (CK_SLIST_EMPTY(NCHHASH(hash)))
1787 goto out_no_entry;
1788
1789 mtx_lock(blp);
1790
1791 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1792 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1793 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1794 break;
1795 }
1796
1797 if (ncp == NULL) {
1798 mtx_unlock(blp);
1799 goto out_no_entry;
1800 }
1801
1802 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
1803 if (__predict_false(error != 0)) {
1804 atomic_add_long(&zap_bucket_fail, 1);
1805 goto retry;
1806 }
1807 counter_u64_add(numposzaps, 1);
1808 SDT_PROBE2(vfs, namecache, removecnp, hit, dvp, cnp);
1809 cache_free(ncp);
1810 return (1);
1811 out_no_entry:
1812 counter_u64_add(nummisszap, 1);
1813 SDT_PROBE2(vfs, namecache, removecnp, miss, dvp, cnp);
1814 return (0);
1815 }
1816
1817 static int __noinline
cache_lookup_dot(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp,struct timespec * tsp,int * ticksp)1818 cache_lookup_dot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1819 struct timespec *tsp, int *ticksp)
1820 {
1821 int ltype;
1822
1823 *vpp = dvp;
1824 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ".", *vpp);
1825 if (tsp != NULL)
1826 timespecclear(tsp);
1827 if (ticksp != NULL)
1828 *ticksp = ticks;
1829 vrefact(*vpp);
1830 /*
1831 * When we lookup "." we still can be asked to lock it
1832 * differently...
1833 */
1834 ltype = cnp->cn_lkflags & LK_TYPE_MASK;
1835 if (ltype != VOP_ISLOCKED(*vpp)) {
1836 if (ltype == LK_EXCLUSIVE) {
1837 vn_lock(*vpp, LK_UPGRADE | LK_RETRY);
1838 if (VN_IS_DOOMED((*vpp))) {
1839 /* forced unmount */
1840 vrele(*vpp);
1841 *vpp = NULL;
1842 return (ENOENT);
1843 }
1844 } else
1845 vn_lock(*vpp, LK_DOWNGRADE | LK_RETRY);
1846 }
1847 return (-1);
1848 }
1849
1850 static int __noinline
cache_lookup_dotdot(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp,struct timespec * tsp,int * ticksp)1851 cache_lookup_dotdot(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1852 struct timespec *tsp, int *ticksp)
1853 {
1854 struct namecache_ts *ncp_ts;
1855 struct namecache *ncp;
1856 struct mtx *dvlp;
1857 enum vgetstate vs;
1858 int error, ltype;
1859 bool whiteout;
1860
1861 MPASS((cnp->cn_flags & ISDOTDOT) != 0);
1862
1863 if ((cnp->cn_flags & MAKEENTRY) == 0) {
1864 cache_remove_cnp(dvp, cnp);
1865 return (0);
1866 }
1867
1868 retry:
1869 dvlp = VP2VNODELOCK(dvp);
1870 mtx_lock(dvlp);
1871 ncp = dvp->v_cache_dd;
1872 if (ncp == NULL) {
1873 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, "..");
1874 mtx_unlock(dvlp);
1875 return (0);
1876 }
1877 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0) {
1878 if (ncp->nc_flag & NCF_NEGATIVE)
1879 *vpp = NULL;
1880 else
1881 *vpp = ncp->nc_vp;
1882 } else
1883 *vpp = ncp->nc_dvp;
1884 if (*vpp == NULL)
1885 goto negative_success;
1886 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, "..", *vpp);
1887 cache_out_ts(ncp, tsp, ticksp);
1888 if ((ncp->nc_flag & (NCF_ISDOTDOT | NCF_DTS)) ==
1889 NCF_DTS && tsp != NULL) {
1890 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
1891 *tsp = ncp_ts->nc_dotdottime;
1892 }
1893
1894 MPASS(dvp != *vpp);
1895 ltype = VOP_ISLOCKED(dvp);
1896 VOP_UNLOCK(dvp);
1897 vs = vget_prep(*vpp);
1898 mtx_unlock(dvlp);
1899 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
1900 vn_lock(dvp, ltype | LK_RETRY);
1901 if (VN_IS_DOOMED(dvp)) {
1902 if (error == 0)
1903 vput(*vpp);
1904 *vpp = NULL;
1905 return (ENOENT);
1906 }
1907 if (error) {
1908 *vpp = NULL;
1909 goto retry;
1910 }
1911 return (-1);
1912 negative_success:
1913 if (__predict_false(cnp->cn_nameiop == CREATE)) {
1914 if (cnp->cn_flags & ISLASTCN) {
1915 counter_u64_add(numnegzaps, 1);
1916 cache_zap_negative_locked_vnode_kl(ncp, dvp);
1917 mtx_unlock(dvlp);
1918 cache_free(ncp);
1919 return (0);
1920 }
1921 }
1922
1923 whiteout = (ncp->nc_flag & NCF_WHITE);
1924 cache_out_ts(ncp, tsp, ticksp);
1925 if (cache_neg_hit_prep(ncp))
1926 cache_neg_promote(ncp);
1927 else
1928 cache_neg_hit_finish(ncp);
1929 mtx_unlock(dvlp);
1930 if (whiteout)
1931 cnp->cn_flags |= ISWHITEOUT;
1932 return (ENOENT);
1933 }
1934
1935 /**
1936 * Lookup a name in the name cache
1937 *
1938 * # Arguments
1939 *
1940 * - dvp: Parent directory in which to search.
1941 * - vpp: Return argument. Will contain desired vnode on cache hit.
1942 * - cnp: Parameters of the name search. The most interesting bits of
1943 * the cn_flags field have the following meanings:
1944 * - MAKEENTRY: If clear, free an entry from the cache rather than look
1945 * it up.
1946 * - ISDOTDOT: Must be set if and only if cn_nameptr == ".."
1947 * - tsp: Return storage for cache timestamp. On a successful (positive
1948 * or negative) lookup, tsp will be filled with any timespec that
1949 * was stored when this cache entry was created. However, it will
1950 * be clear for "." entries.
1951 * - ticks: Return storage for alternate cache timestamp. On a successful
1952 * (positive or negative) lookup, it will contain the ticks value
1953 * that was current when the cache entry was created, unless cnp
1954 * was ".".
1955 *
1956 * Either both tsp and ticks have to be provided or neither of them.
1957 *
1958 * # Returns
1959 *
1960 * - -1: A positive cache hit. vpp will contain the desired vnode.
1961 * - ENOENT: A negative cache hit, or dvp was recycled out from under us due
1962 * to a forced unmount. vpp will not be modified. If the entry
1963 * is a whiteout, then the ISWHITEOUT flag will be set in
1964 * cnp->cn_flags.
1965 * - 0: A cache miss. vpp will not be modified.
1966 *
1967 * # Locking
1968 *
1969 * On a cache hit, vpp will be returned locked and ref'd. If we're looking up
1970 * .., dvp is unlocked. If we're looking up . an extra ref is taken, but the
1971 * lock is not recursively acquired.
1972 */
1973 static int __noinline
cache_lookup_fallback(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp,struct timespec * tsp,int * ticksp)1974 cache_lookup_fallback(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
1975 struct timespec *tsp, int *ticksp)
1976 {
1977 struct namecache *ncp;
1978 struct mtx *blp;
1979 uint32_t hash;
1980 enum vgetstate vs;
1981 int error;
1982 bool whiteout;
1983
1984 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
1985 MPASS((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) != 0);
1986
1987 retry:
1988 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
1989 blp = HASH2BUCKETLOCK(hash);
1990 mtx_lock(blp);
1991
1992 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
1993 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
1994 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
1995 break;
1996 }
1997
1998 if (__predict_false(ncp == NULL)) {
1999 mtx_unlock(blp);
2000 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2001 counter_u64_add(nummiss, 1);
2002 return (0);
2003 }
2004
2005 if (ncp->nc_flag & NCF_NEGATIVE)
2006 goto negative_success;
2007
2008 counter_u64_add(numposhits, 1);
2009 *vpp = ncp->nc_vp;
2010 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2011 cache_out_ts(ncp, tsp, ticksp);
2012 MPASS(dvp != *vpp);
2013 vs = vget_prep(*vpp);
2014 mtx_unlock(blp);
2015 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2016 if (error) {
2017 *vpp = NULL;
2018 goto retry;
2019 }
2020 return (-1);
2021 negative_success:
2022 /*
2023 * We don't get here with regular lookup apart from corner cases.
2024 */
2025 if (__predict_true(cnp->cn_nameiop == CREATE)) {
2026 if (cnp->cn_flags & ISLASTCN) {
2027 counter_u64_add(numnegzaps, 1);
2028 error = cache_zap_locked_bucket(ncp, cnp, hash, blp);
2029 if (__predict_false(error != 0)) {
2030 atomic_add_long(&zap_bucket_fail2, 1);
2031 goto retry;
2032 }
2033 cache_free(ncp);
2034 return (0);
2035 }
2036 }
2037
2038 whiteout = (ncp->nc_flag & NCF_WHITE);
2039 cache_out_ts(ncp, tsp, ticksp);
2040 if (cache_neg_hit_prep(ncp))
2041 cache_neg_promote(ncp);
2042 else
2043 cache_neg_hit_finish(ncp);
2044 mtx_unlock(blp);
2045 if (whiteout)
2046 cnp->cn_flags |= ISWHITEOUT;
2047 return (ENOENT);
2048 }
2049
2050 int
cache_lookup(struct vnode * dvp,struct vnode ** vpp,struct componentname * cnp,struct timespec * tsp,int * ticksp)2051 cache_lookup(struct vnode *dvp, struct vnode **vpp, struct componentname *cnp,
2052 struct timespec *tsp, int *ticksp)
2053 {
2054 struct namecache *ncp;
2055 uint32_t hash;
2056 enum vgetstate vs;
2057 int error;
2058 bool whiteout, neg_promote;
2059 u_short nc_flag;
2060
2061 MPASS((tsp == NULL && ticksp == NULL) || (tsp != NULL && ticksp != NULL));
2062
2063 #ifdef DEBUG_CACHE
2064 if (__predict_false(!doingcache)) {
2065 cnp->cn_flags &= ~MAKEENTRY;
2066 return (0);
2067 }
2068 #endif
2069
2070 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2071 if (cnp->cn_namelen == 1)
2072 return (cache_lookup_dot(dvp, vpp, cnp, tsp, ticksp));
2073 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.')
2074 return (cache_lookup_dotdot(dvp, vpp, cnp, tsp, ticksp));
2075 }
2076
2077 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
2078
2079 if ((cnp->cn_flags & (MAKEENTRY | NC_KEEPPOSENTRY)) == 0) {
2080 cache_remove_cnp(dvp, cnp);
2081 return (0);
2082 }
2083
2084 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
2085 vfs_smr_enter();
2086
2087 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
2088 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
2089 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
2090 break;
2091 }
2092
2093 if (__predict_false(ncp == NULL)) {
2094 vfs_smr_exit();
2095 SDT_PROBE2(vfs, namecache, lookup, miss, dvp, cnp->cn_nameptr);
2096 counter_u64_add(nummiss, 1);
2097 return (0);
2098 }
2099
2100 nc_flag = atomic_load_char(&ncp->nc_flag);
2101 if (nc_flag & NCF_NEGATIVE)
2102 goto negative_success;
2103
2104 counter_u64_add(numposhits, 1);
2105 *vpp = ncp->nc_vp;
2106 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, *vpp);
2107 cache_out_ts(ncp, tsp, ticksp);
2108 MPASS(dvp != *vpp);
2109 if (!cache_ncp_canuse(ncp)) {
2110 vfs_smr_exit();
2111 *vpp = NULL;
2112 goto out_fallback;
2113 }
2114 vs = vget_prep_smr(*vpp);
2115 vfs_smr_exit();
2116 if (__predict_false(vs == VGET_NONE)) {
2117 *vpp = NULL;
2118 goto out_fallback;
2119 }
2120 error = vget_finish(*vpp, cnp->cn_lkflags, vs);
2121 if (error) {
2122 *vpp = NULL;
2123 goto out_fallback;
2124 }
2125 return (-1);
2126 negative_success:
2127 if (cnp->cn_nameiop == CREATE) {
2128 if (cnp->cn_flags & ISLASTCN) {
2129 vfs_smr_exit();
2130 goto out_fallback;
2131 }
2132 }
2133
2134 cache_out_ts(ncp, tsp, ticksp);
2135 whiteout = (atomic_load_char(&ncp->nc_flag) & NCF_WHITE);
2136 neg_promote = cache_neg_hit_prep(ncp);
2137 if (!cache_ncp_canuse(ncp)) {
2138 cache_neg_hit_abort(ncp);
2139 vfs_smr_exit();
2140 goto out_fallback;
2141 }
2142 if (neg_promote) {
2143 vfs_smr_exit();
2144 if (!cache_neg_promote_cond(dvp, cnp, ncp, hash))
2145 goto out_fallback;
2146 } else {
2147 cache_neg_hit_finish(ncp);
2148 vfs_smr_exit();
2149 }
2150 if (whiteout)
2151 cnp->cn_flags |= ISWHITEOUT;
2152 return (ENOENT);
2153 out_fallback:
2154 return (cache_lookup_fallback(dvp, vpp, cnp, tsp, ticksp));
2155 }
2156
2157 struct celockstate {
2158 struct mtx *vlp[3];
2159 struct mtx *blp[2];
2160 };
2161 CTASSERT((nitems(((struct celockstate *)0)->vlp) == 3));
2162 CTASSERT((nitems(((struct celockstate *)0)->blp) == 2));
2163
2164 static inline void
cache_celockstate_init(struct celockstate * cel)2165 cache_celockstate_init(struct celockstate *cel)
2166 {
2167
2168 bzero(cel, sizeof(*cel));
2169 }
2170
2171 static void
cache_lock_vnodes_cel(struct celockstate * cel,struct vnode * vp,struct vnode * dvp)2172 cache_lock_vnodes_cel(struct celockstate *cel, struct vnode *vp,
2173 struct vnode *dvp)
2174 {
2175 struct mtx *vlp1, *vlp2;
2176
2177 MPASS(cel->vlp[0] == NULL);
2178 MPASS(cel->vlp[1] == NULL);
2179 MPASS(cel->vlp[2] == NULL);
2180
2181 MPASS(vp != NULL || dvp != NULL);
2182
2183 vlp1 = VP2VNODELOCK(vp);
2184 vlp2 = VP2VNODELOCK(dvp);
2185 cache_sort_vnodes(&vlp1, &vlp2);
2186
2187 if (vlp1 != NULL) {
2188 mtx_lock(vlp1);
2189 cel->vlp[0] = vlp1;
2190 }
2191 mtx_lock(vlp2);
2192 cel->vlp[1] = vlp2;
2193 }
2194
2195 static void
cache_unlock_vnodes_cel(struct celockstate * cel)2196 cache_unlock_vnodes_cel(struct celockstate *cel)
2197 {
2198
2199 MPASS(cel->vlp[0] != NULL || cel->vlp[1] != NULL);
2200
2201 if (cel->vlp[0] != NULL)
2202 mtx_unlock(cel->vlp[0]);
2203 if (cel->vlp[1] != NULL)
2204 mtx_unlock(cel->vlp[1]);
2205 if (cel->vlp[2] != NULL)
2206 mtx_unlock(cel->vlp[2]);
2207 }
2208
2209 static bool
cache_lock_vnodes_cel_3(struct celockstate * cel,struct vnode * vp)2210 cache_lock_vnodes_cel_3(struct celockstate *cel, struct vnode *vp)
2211 {
2212 struct mtx *vlp;
2213 bool ret;
2214
2215 cache_assert_vlp_locked(cel->vlp[0]);
2216 cache_assert_vlp_locked(cel->vlp[1]);
2217 MPASS(cel->vlp[2] == NULL);
2218
2219 MPASS(vp != NULL);
2220 vlp = VP2VNODELOCK(vp);
2221
2222 ret = true;
2223 if (vlp >= cel->vlp[1]) {
2224 mtx_lock(vlp);
2225 } else {
2226 if (mtx_trylock(vlp))
2227 goto out;
2228 cache_unlock_vnodes_cel(cel);
2229 atomic_add_long(&cache_lock_vnodes_cel_3_failures, 1);
2230 if (vlp < cel->vlp[0]) {
2231 mtx_lock(vlp);
2232 mtx_lock(cel->vlp[0]);
2233 mtx_lock(cel->vlp[1]);
2234 } else {
2235 if (cel->vlp[0] != NULL)
2236 mtx_lock(cel->vlp[0]);
2237 mtx_lock(vlp);
2238 mtx_lock(cel->vlp[1]);
2239 }
2240 ret = false;
2241 }
2242 out:
2243 cel->vlp[2] = vlp;
2244 return (ret);
2245 }
2246
2247 static void
cache_lock_buckets_cel(struct celockstate * cel,struct mtx * blp1,struct mtx * blp2)2248 cache_lock_buckets_cel(struct celockstate *cel, struct mtx *blp1,
2249 struct mtx *blp2)
2250 {
2251
2252 MPASS(cel->blp[0] == NULL);
2253 MPASS(cel->blp[1] == NULL);
2254
2255 cache_sort_vnodes(&blp1, &blp2);
2256
2257 if (blp1 != NULL) {
2258 mtx_lock(blp1);
2259 cel->blp[0] = blp1;
2260 }
2261 mtx_lock(blp2);
2262 cel->blp[1] = blp2;
2263 }
2264
2265 static void
cache_unlock_buckets_cel(struct celockstate * cel)2266 cache_unlock_buckets_cel(struct celockstate *cel)
2267 {
2268
2269 if (cel->blp[0] != NULL)
2270 mtx_unlock(cel->blp[0]);
2271 mtx_unlock(cel->blp[1]);
2272 }
2273
2274 /*
2275 * Lock part of the cache affected by the insertion.
2276 *
2277 * This means vnodelocks for dvp, vp and the relevant bucketlock.
2278 * However, insertion can result in removal of an old entry. In this
2279 * case we have an additional vnode and bucketlock pair to lock.
2280 *
2281 * That is, in the worst case we have to lock 3 vnodes and 2 bucketlocks, while
2282 * preserving the locking order (smaller address first).
2283 */
2284 static void
cache_enter_lock(struct celockstate * cel,struct vnode * dvp,struct vnode * vp,uint32_t hash)2285 cache_enter_lock(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2286 uint32_t hash)
2287 {
2288 struct namecache *ncp;
2289 struct mtx *blps[2];
2290 u_char nc_flag;
2291
2292 blps[0] = HASH2BUCKETLOCK(hash);
2293 for (;;) {
2294 blps[1] = NULL;
2295 cache_lock_vnodes_cel(cel, dvp, vp);
2296 if (vp == NULL || vp->v_type != VDIR)
2297 break;
2298 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
2299 if (ncp == NULL)
2300 break;
2301 nc_flag = atomic_load_char(&ncp->nc_flag);
2302 if ((nc_flag & NCF_ISDOTDOT) == 0)
2303 break;
2304 MPASS(ncp->nc_dvp == vp);
2305 blps[1] = NCP2BUCKETLOCK(ncp);
2306 if ((nc_flag & NCF_NEGATIVE) != 0)
2307 break;
2308 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2309 break;
2310 /*
2311 * All vnodes got re-locked. Re-validate the state and if
2312 * nothing changed we are done. Otherwise restart.
2313 */
2314 if (ncp == vp->v_cache_dd &&
2315 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2316 blps[1] == NCP2BUCKETLOCK(ncp) &&
2317 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2318 break;
2319 cache_unlock_vnodes_cel(cel);
2320 cel->vlp[0] = NULL;
2321 cel->vlp[1] = NULL;
2322 cel->vlp[2] = NULL;
2323 }
2324 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2325 }
2326
2327 static void
cache_enter_lock_dd(struct celockstate * cel,struct vnode * dvp,struct vnode * vp,uint32_t hash)2328 cache_enter_lock_dd(struct celockstate *cel, struct vnode *dvp, struct vnode *vp,
2329 uint32_t hash)
2330 {
2331 struct namecache *ncp;
2332 struct mtx *blps[2];
2333 u_char nc_flag;
2334
2335 blps[0] = HASH2BUCKETLOCK(hash);
2336 for (;;) {
2337 blps[1] = NULL;
2338 cache_lock_vnodes_cel(cel, dvp, vp);
2339 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
2340 if (ncp == NULL)
2341 break;
2342 nc_flag = atomic_load_char(&ncp->nc_flag);
2343 if ((nc_flag & NCF_ISDOTDOT) == 0)
2344 break;
2345 MPASS(ncp->nc_dvp == dvp);
2346 blps[1] = NCP2BUCKETLOCK(ncp);
2347 if ((nc_flag & NCF_NEGATIVE) != 0)
2348 break;
2349 if (cache_lock_vnodes_cel_3(cel, ncp->nc_vp))
2350 break;
2351 if (ncp == dvp->v_cache_dd &&
2352 (ncp->nc_flag & NCF_ISDOTDOT) != 0 &&
2353 blps[1] == NCP2BUCKETLOCK(ncp) &&
2354 VP2VNODELOCK(ncp->nc_vp) == cel->vlp[2])
2355 break;
2356 cache_unlock_vnodes_cel(cel);
2357 cel->vlp[0] = NULL;
2358 cel->vlp[1] = NULL;
2359 cel->vlp[2] = NULL;
2360 }
2361 cache_lock_buckets_cel(cel, blps[0], blps[1]);
2362 }
2363
2364 static void
cache_enter_unlock(struct celockstate * cel)2365 cache_enter_unlock(struct celockstate *cel)
2366 {
2367
2368 cache_unlock_buckets_cel(cel);
2369 cache_unlock_vnodes_cel(cel);
2370 }
2371
2372 static void __noinline
cache_enter_dotdot_prep(struct vnode * dvp,struct vnode * vp,struct componentname * cnp)2373 cache_enter_dotdot_prep(struct vnode *dvp, struct vnode *vp,
2374 struct componentname *cnp)
2375 {
2376 struct celockstate cel;
2377 struct namecache *ncp;
2378 uint32_t hash;
2379 int len;
2380
2381 if (atomic_load_ptr(&dvp->v_cache_dd) == NULL)
2382 return;
2383 len = cnp->cn_namelen;
2384 cache_celockstate_init(&cel);
2385 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2386 cache_enter_lock_dd(&cel, dvp, vp, hash);
2387 ncp = dvp->v_cache_dd;
2388 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT)) {
2389 KASSERT(ncp->nc_dvp == dvp, ("wrong isdotdot parent"));
2390 cache_zap_locked(ncp);
2391 } else {
2392 ncp = NULL;
2393 }
2394 atomic_store_ptr(&dvp->v_cache_dd, NULL);
2395 cache_enter_unlock(&cel);
2396 if (ncp != NULL)
2397 cache_free(ncp);
2398 }
2399
2400 /*
2401 * Add an entry to the cache.
2402 */
2403 void
cache_enter_time(struct vnode * dvp,struct vnode * vp,struct componentname * cnp,struct timespec * tsp,struct timespec * dtsp)2404 cache_enter_time(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2405 struct timespec *tsp, struct timespec *dtsp)
2406 {
2407 struct celockstate cel;
2408 struct namecache *ncp, *n2, *ndd;
2409 struct namecache_ts *ncp_ts;
2410 struct nchashhead *ncpp;
2411 uint32_t hash;
2412 int flag;
2413 int len;
2414
2415 KASSERT(cnp->cn_namelen <= NAME_MAX,
2416 ("%s: passed len %ld exceeds NAME_MAX (%d)", __func__, cnp->cn_namelen,
2417 NAME_MAX));
2418 VNPASS(!VN_IS_DOOMED(dvp), dvp);
2419 VNPASS(dvp->v_type != VNON, dvp);
2420 if (vp != NULL) {
2421 VNPASS(!VN_IS_DOOMED(vp), vp);
2422 VNPASS(vp->v_type != VNON, vp);
2423 }
2424 if (cnp->cn_namelen == 1 && cnp->cn_nameptr[0] == '.') {
2425 KASSERT(dvp == vp,
2426 ("%s: different vnodes for dot entry (%p; %p)\n", __func__,
2427 dvp, vp));
2428 } else {
2429 KASSERT(dvp != vp,
2430 ("%s: same vnode for non-dot entry [%s] (%p)\n", __func__,
2431 cnp->cn_nameptr, dvp));
2432 }
2433
2434 #ifdef DEBUG_CACHE
2435 if (__predict_false(!doingcache))
2436 return;
2437 #endif
2438
2439 flag = 0;
2440 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
2441 if (cnp->cn_namelen == 1)
2442 return;
2443 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
2444 cache_enter_dotdot_prep(dvp, vp, cnp);
2445 flag = NCF_ISDOTDOT;
2446 }
2447 }
2448
2449 ncp = cache_alloc(cnp->cn_namelen, tsp != NULL);
2450 if (ncp == NULL)
2451 return;
2452
2453 cache_celockstate_init(&cel);
2454 ndd = NULL;
2455 ncp_ts = NULL;
2456
2457 /*
2458 * Calculate the hash key and setup as much of the new
2459 * namecache entry as possible before acquiring the lock.
2460 */
2461 ncp->nc_flag = flag | NCF_WIP;
2462 ncp->nc_vp = vp;
2463 if (vp == NULL)
2464 cache_neg_init(ncp);
2465 ncp->nc_dvp = dvp;
2466 if (tsp != NULL) {
2467 ncp_ts = __containerof(ncp, struct namecache_ts, nc_nc);
2468 ncp_ts->nc_time = *tsp;
2469 ncp_ts->nc_ticks = ticks;
2470 ncp_ts->nc_nc.nc_flag |= NCF_TS;
2471 if (dtsp != NULL) {
2472 ncp_ts->nc_dotdottime = *dtsp;
2473 ncp_ts->nc_nc.nc_flag |= NCF_DTS;
2474 }
2475 }
2476 len = ncp->nc_nlen = cnp->cn_namelen;
2477 hash = cache_get_hash(cnp->cn_nameptr, len, dvp);
2478 memcpy(ncp->nc_name, cnp->cn_nameptr, len);
2479 ncp->nc_name[len] = '\0';
2480 cache_enter_lock(&cel, dvp, vp, hash);
2481
2482 /*
2483 * See if this vnode or negative entry is already in the cache
2484 * with this name. This can happen with concurrent lookups of
2485 * the same path name.
2486 */
2487 ncpp = NCHHASH(hash);
2488 CK_SLIST_FOREACH(n2, ncpp, nc_hash) {
2489 if (n2->nc_dvp == dvp &&
2490 n2->nc_nlen == cnp->cn_namelen &&
2491 !bcmp(n2->nc_name, cnp->cn_nameptr, n2->nc_nlen)) {
2492 MPASS(cache_ncp_canuse(n2));
2493 if ((n2->nc_flag & NCF_NEGATIVE) != 0)
2494 KASSERT(vp == NULL,
2495 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2496 __func__, NULL, vp, cnp->cn_nameptr));
2497 else
2498 KASSERT(n2->nc_vp == vp,
2499 ("%s: found entry pointing to a different vnode (%p != %p) ; name [%s]",
2500 __func__, n2->nc_vp, vp, cnp->cn_nameptr));
2501 /*
2502 * Entries are supposed to be immutable unless in the
2503 * process of getting destroyed. Accommodating for
2504 * changing timestamps is possible but not worth it.
2505 * This should be harmless in terms of correctness, in
2506 * the worst case resulting in an earlier expiration.
2507 * Alternatively, the found entry can be replaced
2508 * altogether.
2509 */
2510 MPASS((n2->nc_flag & (NCF_TS | NCF_DTS)) == (ncp->nc_flag & (NCF_TS | NCF_DTS)));
2511 #if 0
2512 if (tsp != NULL) {
2513 KASSERT((n2->nc_flag & NCF_TS) != 0,
2514 ("no NCF_TS"));
2515 n2_ts = __containerof(n2, struct namecache_ts, nc_nc);
2516 n2_ts->nc_time = ncp_ts->nc_time;
2517 n2_ts->nc_ticks = ncp_ts->nc_ticks;
2518 if (dtsp != NULL) {
2519 n2_ts->nc_dotdottime = ncp_ts->nc_dotdottime;
2520 n2_ts->nc_nc.nc_flag |= NCF_DTS;
2521 }
2522 }
2523 #endif
2524 SDT_PROBE3(vfs, namecache, enter, duplicate, dvp, ncp->nc_name,
2525 vp);
2526 goto out_unlock_free;
2527 }
2528 }
2529
2530 if (flag == NCF_ISDOTDOT) {
2531 /*
2532 * See if we are trying to add .. entry, but some other lookup
2533 * has populated v_cache_dd pointer already.
2534 */
2535 if (dvp->v_cache_dd != NULL)
2536 goto out_unlock_free;
2537 KASSERT(vp == NULL || vp->v_type == VDIR,
2538 ("wrong vnode type %p", vp));
2539 atomic_thread_fence_rel();
2540 atomic_store_ptr(&dvp->v_cache_dd, ncp);
2541 }
2542
2543 if (vp != NULL) {
2544 if (flag != NCF_ISDOTDOT) {
2545 /*
2546 * For this case, the cache entry maps both the
2547 * directory name in it and the name ".." for the
2548 * directory's parent.
2549 */
2550 if ((ndd = vp->v_cache_dd) != NULL) {
2551 if ((ndd->nc_flag & NCF_ISDOTDOT) != 0)
2552 cache_zap_locked(ndd);
2553 else
2554 ndd = NULL;
2555 }
2556 atomic_thread_fence_rel();
2557 atomic_store_ptr(&vp->v_cache_dd, ncp);
2558 } else if (vp->v_type != VDIR) {
2559 if (vp->v_cache_dd != NULL) {
2560 atomic_store_ptr(&vp->v_cache_dd, NULL);
2561 }
2562 }
2563 }
2564
2565 if (flag != NCF_ISDOTDOT) {
2566 if (LIST_EMPTY(&dvp->v_cache_src)) {
2567 cache_hold_vnode(dvp);
2568 }
2569 LIST_INSERT_HEAD(&dvp->v_cache_src, ncp, nc_src);
2570 }
2571
2572 /*
2573 * If the entry is "negative", we place it into the
2574 * "negative" cache queue, otherwise, we place it into the
2575 * destination vnode's cache entries queue.
2576 */
2577 if (vp != NULL) {
2578 TAILQ_INSERT_HEAD(&vp->v_cache_dst, ncp, nc_dst);
2579 SDT_PROBE3(vfs, namecache, enter, done, dvp, ncp->nc_name,
2580 vp);
2581 } else {
2582 if (cnp->cn_flags & ISWHITEOUT)
2583 atomic_store_char(&ncp->nc_flag, ncp->nc_flag | NCF_WHITE);
2584 cache_neg_insert(ncp);
2585 SDT_PROBE2(vfs, namecache, enter_negative, done, dvp,
2586 ncp->nc_name);
2587 }
2588
2589 /*
2590 * Insert the new namecache entry into the appropriate chain
2591 * within the cache entries table.
2592 */
2593 CK_SLIST_INSERT_HEAD(ncpp, ncp, nc_hash);
2594
2595 atomic_thread_fence_rel();
2596 /*
2597 * Mark the entry as fully constructed.
2598 * It is immutable past this point until its removal.
2599 */
2600 atomic_store_char(&ncp->nc_flag, ncp->nc_flag & ~NCF_WIP);
2601
2602 cache_enter_unlock(&cel);
2603 if (ndd != NULL)
2604 cache_free(ndd);
2605 return;
2606 out_unlock_free:
2607 cache_enter_unlock(&cel);
2608 cache_free(ncp);
2609 return;
2610 }
2611
2612 /*
2613 * A variant of the above accepting flags.
2614 *
2615 * - VFS_CACHE_DROPOLD -- if a conflicting entry is found, drop it.
2616 *
2617 * TODO: this routine is a hack. It blindly removes the old entry, even if it
2618 * happens to match and it is doing it in an inefficient manner. It was added
2619 * to accommodate NFS which runs into a case where the target for a given name
2620 * may change from under it. Note this does nothing to solve the following
2621 * race: 2 callers of cache_enter_time_flags pass a different target vnode for
2622 * the same [dvp, cnp]. It may be argued that code doing this is broken.
2623 */
2624 void
cache_enter_time_flags(struct vnode * dvp,struct vnode * vp,struct componentname * cnp,struct timespec * tsp,struct timespec * dtsp,int flags)2625 cache_enter_time_flags(struct vnode *dvp, struct vnode *vp, struct componentname *cnp,
2626 struct timespec *tsp, struct timespec *dtsp, int flags)
2627 {
2628
2629 MPASS((flags & ~(VFS_CACHE_DROPOLD)) == 0);
2630
2631 if (flags & VFS_CACHE_DROPOLD)
2632 cache_remove_cnp(dvp, cnp);
2633 cache_enter_time(dvp, vp, cnp, tsp, dtsp);
2634 }
2635
2636 static u_long
cache_roundup_2(u_long val)2637 cache_roundup_2(u_long val)
2638 {
2639 u_long res;
2640
2641 for (res = 1; res <= val; res <<= 1)
2642 continue;
2643
2644 return (res);
2645 }
2646
2647 static struct nchashhead *
nchinittbl(u_long elements,u_long * hashmask)2648 nchinittbl(u_long elements, u_long *hashmask)
2649 {
2650 struct nchashhead *hashtbl;
2651 u_long hashsize, i;
2652
2653 hashsize = cache_roundup_2(elements) / 2;
2654
2655 hashtbl = malloc(hashsize * sizeof(*hashtbl), M_VFSCACHE, M_WAITOK);
2656 for (i = 0; i < hashsize; i++)
2657 CK_SLIST_INIT(&hashtbl[i]);
2658 *hashmask = hashsize - 1;
2659 return (hashtbl);
2660 }
2661
2662 static void
ncfreetbl(struct nchashhead * hashtbl)2663 ncfreetbl(struct nchashhead *hashtbl)
2664 {
2665
2666 free(hashtbl, M_VFSCACHE);
2667 }
2668
2669 /*
2670 * Name cache initialization, from vfs_init() when we are booting
2671 */
2672 static void
nchinit(void * dummy __unused)2673 nchinit(void *dummy __unused)
2674 {
2675 u_int i;
2676
2677 cache_zone_small = uma_zcreate("S VFS Cache", CACHE_ZONE_SMALL_SIZE,
2678 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2679 cache_zone_small_ts = uma_zcreate("STS VFS Cache", CACHE_ZONE_SMALL_TS_SIZE,
2680 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2681 cache_zone_large = uma_zcreate("L VFS Cache", CACHE_ZONE_LARGE_SIZE,
2682 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2683 cache_zone_large_ts = uma_zcreate("LTS VFS Cache", CACHE_ZONE_LARGE_TS_SIZE,
2684 NULL, NULL, NULL, NULL, CACHE_ZONE_ALIGNMENT, UMA_ZONE_ZINIT);
2685
2686 VFS_SMR_ZONE_SET(cache_zone_small);
2687 VFS_SMR_ZONE_SET(cache_zone_small_ts);
2688 VFS_SMR_ZONE_SET(cache_zone_large);
2689 VFS_SMR_ZONE_SET(cache_zone_large_ts);
2690
2691 ncsize = desiredvnodes * ncsizefactor;
2692 cache_recalc_neg_min();
2693 nchashtbl = nchinittbl(desiredvnodes * 2, &nchash);
2694 ncbuckethash = cache_roundup_2(mp_ncpus * mp_ncpus) - 1;
2695 if (ncbuckethash < 7) /* arbitrarily chosen to avoid having one lock */
2696 ncbuckethash = 7;
2697 if (ncbuckethash > nchash)
2698 ncbuckethash = nchash;
2699 bucketlocks = malloc(sizeof(*bucketlocks) * numbucketlocks, M_VFSCACHE,
2700 M_WAITOK | M_ZERO);
2701 for (i = 0; i < numbucketlocks; i++)
2702 mtx_init(&bucketlocks[i], "ncbuc", NULL, MTX_DUPOK | MTX_RECURSE);
2703 ncvnodehash = ncbuckethash;
2704 vnodelocks = malloc(sizeof(*vnodelocks) * numvnodelocks, M_VFSCACHE,
2705 M_WAITOK | M_ZERO);
2706 for (i = 0; i < numvnodelocks; i++)
2707 mtx_init(&vnodelocks[i], "ncvn", NULL, MTX_DUPOK | MTX_RECURSE);
2708
2709 for (i = 0; i < numneglists; i++) {
2710 mtx_init(&neglists[i].nl_evict_lock, "ncnege", NULL, MTX_DEF);
2711 mtx_init(&neglists[i].nl_lock, "ncnegl", NULL, MTX_DEF);
2712 TAILQ_INIT(&neglists[i].nl_list);
2713 TAILQ_INIT(&neglists[i].nl_hotlist);
2714 }
2715 }
2716 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_SECOND, nchinit, NULL);
2717
2718 void
cache_vnode_init(struct vnode * vp)2719 cache_vnode_init(struct vnode *vp)
2720 {
2721
2722 LIST_INIT(&vp->v_cache_src);
2723 TAILQ_INIT(&vp->v_cache_dst);
2724 vp->v_cache_dd = NULL;
2725 cache_prehash(vp);
2726 }
2727
2728 /*
2729 * Induce transient cache misses for lockless operation in cache_lookup() by
2730 * using a temporary hash table.
2731 *
2732 * This will force a fs lookup.
2733 *
2734 * Synchronisation is done in 2 steps, calling vfs_smr_synchronize each time
2735 * to observe all CPUs not performing the lookup.
2736 */
2737 static void
cache_changesize_set_temp(struct nchashhead * temptbl,u_long temphash)2738 cache_changesize_set_temp(struct nchashhead *temptbl, u_long temphash)
2739 {
2740
2741 MPASS(temphash < nchash);
2742 /*
2743 * Change the size. The new size is smaller and can safely be used
2744 * against the existing table. All lookups which now hash wrong will
2745 * result in a cache miss, which all callers are supposed to know how
2746 * to handle.
2747 */
2748 atomic_store_long(&nchash, temphash);
2749 atomic_thread_fence_rel();
2750 vfs_smr_synchronize();
2751 /*
2752 * At this point everyone sees the updated hash value, but they still
2753 * see the old table.
2754 */
2755 atomic_store_ptr(&nchashtbl, temptbl);
2756 atomic_thread_fence_rel();
2757 vfs_smr_synchronize();
2758 /*
2759 * At this point everyone sees the updated table pointer and size pair.
2760 */
2761 }
2762
2763 /*
2764 * Set the new hash table.
2765 *
2766 * Similarly to cache_changesize_set_temp(), this has to synchronize against
2767 * lockless operation in cache_lookup().
2768 */
2769 static void
cache_changesize_set_new(struct nchashhead * new_tbl,u_long new_hash)2770 cache_changesize_set_new(struct nchashhead *new_tbl, u_long new_hash)
2771 {
2772
2773 MPASS(nchash < new_hash);
2774 /*
2775 * Change the pointer first. This wont result in out of bounds access
2776 * since the temporary table is guaranteed to be smaller.
2777 */
2778 atomic_store_ptr(&nchashtbl, new_tbl);
2779 atomic_thread_fence_rel();
2780 vfs_smr_synchronize();
2781 /*
2782 * At this point everyone sees the updated pointer value, but they
2783 * still see the old size.
2784 */
2785 atomic_store_long(&nchash, new_hash);
2786 atomic_thread_fence_rel();
2787 vfs_smr_synchronize();
2788 /*
2789 * At this point everyone sees the updated table pointer and size pair.
2790 */
2791 }
2792
2793 void
cache_changesize(u_long newmaxvnodes)2794 cache_changesize(u_long newmaxvnodes)
2795 {
2796 struct nchashhead *new_nchashtbl, *old_nchashtbl, *temptbl;
2797 u_long new_nchash, old_nchash, temphash;
2798 struct namecache *ncp;
2799 uint32_t hash;
2800 u_long newncsize;
2801 u_long i;
2802
2803 newncsize = newmaxvnodes * ncsizefactor;
2804 newmaxvnodes = cache_roundup_2(newmaxvnodes * 2);
2805 if (newmaxvnodes < numbucketlocks)
2806 newmaxvnodes = numbucketlocks;
2807
2808 new_nchashtbl = nchinittbl(newmaxvnodes, &new_nchash);
2809 /* If same hash table size, nothing to do */
2810 if (nchash == new_nchash) {
2811 ncfreetbl(new_nchashtbl);
2812 return;
2813 }
2814
2815 temptbl = nchinittbl(1, &temphash);
2816
2817 /*
2818 * Move everything from the old hash table to the new table.
2819 * None of the namecache entries in the table can be removed
2820 * because to do so, they have to be removed from the hash table.
2821 */
2822 cache_lock_all_vnodes();
2823 cache_lock_all_buckets();
2824 old_nchashtbl = nchashtbl;
2825 old_nchash = nchash;
2826 cache_changesize_set_temp(temptbl, temphash);
2827 for (i = 0; i <= old_nchash; i++) {
2828 while ((ncp = CK_SLIST_FIRST(&old_nchashtbl[i])) != NULL) {
2829 hash = cache_get_hash(ncp->nc_name, ncp->nc_nlen,
2830 ncp->nc_dvp);
2831 CK_SLIST_REMOVE(&old_nchashtbl[i], ncp, namecache, nc_hash);
2832 CK_SLIST_INSERT_HEAD(&new_nchashtbl[hash & new_nchash], ncp, nc_hash);
2833 }
2834 }
2835 ncsize = newncsize;
2836 cache_recalc_neg_min();
2837 cache_changesize_set_new(new_nchashtbl, new_nchash);
2838 cache_unlock_all_buckets();
2839 cache_unlock_all_vnodes();
2840 ncfreetbl(old_nchashtbl);
2841 ncfreetbl(temptbl);
2842 }
2843
2844 /*
2845 * Remove all entries from and to a particular vnode.
2846 */
2847 static void
cache_purge_impl(struct vnode * vp)2848 cache_purge_impl(struct vnode *vp)
2849 {
2850 struct cache_freebatch batch;
2851 struct namecache *ncp;
2852 struct mtx *vlp, *vlp2;
2853
2854 TAILQ_INIT(&batch);
2855 vlp = VP2VNODELOCK(vp);
2856 vlp2 = NULL;
2857 mtx_lock(vlp);
2858 retry:
2859 while (!LIST_EMPTY(&vp->v_cache_src)) {
2860 ncp = LIST_FIRST(&vp->v_cache_src);
2861 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2862 goto retry;
2863 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2864 }
2865 while (!TAILQ_EMPTY(&vp->v_cache_dst)) {
2866 ncp = TAILQ_FIRST(&vp->v_cache_dst);
2867 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2868 goto retry;
2869 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2870 }
2871 ncp = vp->v_cache_dd;
2872 if (ncp != NULL) {
2873 KASSERT(ncp->nc_flag & NCF_ISDOTDOT,
2874 ("lost dotdot link"));
2875 if (!cache_zap_locked_vnode_kl2(ncp, vp, &vlp2))
2876 goto retry;
2877 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2878 }
2879 KASSERT(vp->v_cache_dd == NULL, ("incomplete purge"));
2880 mtx_unlock(vlp);
2881 if (vlp2 != NULL)
2882 mtx_unlock(vlp2);
2883 cache_free_batch(&batch);
2884 }
2885
2886 /*
2887 * Opportunistic check to see if there is anything to do.
2888 */
2889 static bool
cache_has_entries(struct vnode * vp)2890 cache_has_entries(struct vnode *vp)
2891 {
2892
2893 if (LIST_EMPTY(&vp->v_cache_src) && TAILQ_EMPTY(&vp->v_cache_dst) &&
2894 atomic_load_ptr(&vp->v_cache_dd) == NULL)
2895 return (false);
2896 return (true);
2897 }
2898
2899 void
cache_purge(struct vnode * vp)2900 cache_purge(struct vnode *vp)
2901 {
2902
2903 SDT_PROBE1(vfs, namecache, purge, done, vp);
2904 if (!cache_has_entries(vp))
2905 return;
2906 cache_purge_impl(vp);
2907 }
2908
2909 /*
2910 * Only to be used by vgone.
2911 */
2912 void
cache_purge_vgone(struct vnode * vp)2913 cache_purge_vgone(struct vnode *vp)
2914 {
2915 struct mtx *vlp;
2916
2917 VNPASS(VN_IS_DOOMED(vp), vp);
2918 if (cache_has_entries(vp)) {
2919 cache_purge_impl(vp);
2920 return;
2921 }
2922
2923 /*
2924 * Serialize against a potential thread doing cache_purge.
2925 */
2926 vlp = VP2VNODELOCK(vp);
2927 mtx_wait_unlocked(vlp);
2928 if (cache_has_entries(vp)) {
2929 cache_purge_impl(vp);
2930 return;
2931 }
2932 return;
2933 }
2934
2935 /*
2936 * Remove all negative entries for a particular directory vnode.
2937 */
2938 void
cache_purge_negative(struct vnode * vp)2939 cache_purge_negative(struct vnode *vp)
2940 {
2941 struct cache_freebatch batch;
2942 struct namecache *ncp, *nnp;
2943 struct mtx *vlp;
2944
2945 SDT_PROBE1(vfs, namecache, purge_negative, done, vp);
2946 if (LIST_EMPTY(&vp->v_cache_src))
2947 return;
2948 TAILQ_INIT(&batch);
2949 vlp = VP2VNODELOCK(vp);
2950 mtx_lock(vlp);
2951 LIST_FOREACH_SAFE(ncp, &vp->v_cache_src, nc_src, nnp) {
2952 if (!(ncp->nc_flag & NCF_NEGATIVE))
2953 continue;
2954 cache_zap_negative_locked_vnode_kl(ncp, vp);
2955 TAILQ_INSERT_TAIL(&batch, ncp, nc_dst);
2956 }
2957 mtx_unlock(vlp);
2958 cache_free_batch(&batch);
2959 }
2960
2961 /*
2962 * Entry points for modifying VOP operations.
2963 */
2964 void
cache_vop_rename(struct vnode * fdvp,struct vnode * fvp,struct vnode * tdvp,struct vnode * tvp,struct componentname * fcnp,struct componentname * tcnp)2965 cache_vop_rename(struct vnode *fdvp, struct vnode *fvp, struct vnode *tdvp,
2966 struct vnode *tvp, struct componentname *fcnp, struct componentname *tcnp)
2967 {
2968
2969 ASSERT_VOP_IN_SEQC(fdvp);
2970 ASSERT_VOP_IN_SEQC(fvp);
2971 ASSERT_VOP_IN_SEQC(tdvp);
2972 if (tvp != NULL)
2973 ASSERT_VOP_IN_SEQC(tvp);
2974
2975 cache_purge(fvp);
2976 if (tvp != NULL) {
2977 cache_purge(tvp);
2978 KASSERT(!cache_remove_cnp(tdvp, tcnp),
2979 ("%s: lingering negative entry", __func__));
2980 } else {
2981 cache_remove_cnp(tdvp, tcnp);
2982 }
2983
2984 /*
2985 * TODO
2986 *
2987 * Historically renaming was always purging all revelang entries,
2988 * but that's quite wasteful. In particular turns out that in many cases
2989 * the target file is immediately accessed after rename, inducing a cache
2990 * miss.
2991 *
2992 * Recode this to reduce relocking and reuse the existing entry (if any)
2993 * instead of just removing it above and allocating a new one here.
2994 */
2995 if (cache_rename_add) {
2996 cache_enter(tdvp, fvp, tcnp);
2997 }
2998 }
2999
3000 void
cache_vop_rmdir(struct vnode * dvp,struct vnode * vp)3001 cache_vop_rmdir(struct vnode *dvp, struct vnode *vp)
3002 {
3003
3004 ASSERT_VOP_IN_SEQC(dvp);
3005 ASSERT_VOP_IN_SEQC(vp);
3006 cache_purge(vp);
3007 }
3008
3009 #ifdef INVARIANTS
3010 /*
3011 * Validate that if an entry exists it matches.
3012 */
3013 void
cache_validate(struct vnode * dvp,struct vnode * vp,struct componentname * cnp)3014 cache_validate(struct vnode *dvp, struct vnode *vp, struct componentname *cnp)
3015 {
3016 struct namecache *ncp;
3017 struct mtx *blp;
3018 uint32_t hash;
3019
3020 hash = cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp);
3021 if (CK_SLIST_EMPTY(NCHHASH(hash)))
3022 return;
3023 blp = HASH2BUCKETLOCK(hash);
3024 mtx_lock(blp);
3025 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
3026 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
3027 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen)) {
3028 if (ncp->nc_vp != vp)
3029 panic("%s: mismatch (%p != %p); ncp %p [%s] dvp %p\n",
3030 __func__, vp, ncp->nc_vp, ncp, ncp->nc_name, ncp->nc_dvp);
3031 }
3032 }
3033 mtx_unlock(blp);
3034 }
3035 #endif
3036
3037 /*
3038 * Flush all entries referencing a particular filesystem.
3039 */
3040 void
cache_purgevfs(struct mount * mp)3041 cache_purgevfs(struct mount *mp)
3042 {
3043 struct vnode *vp, *mvp;
3044 size_t visited, purged;
3045
3046 visited = purged = 0;
3047 /*
3048 * Somewhat wasteful iteration over all vnodes. Would be better to
3049 * support filtering and avoid the interlock to begin with.
3050 */
3051 MNT_VNODE_FOREACH_ALL(vp, mp, mvp) {
3052 visited++;
3053 if (!cache_has_entries(vp)) {
3054 VI_UNLOCK(vp);
3055 continue;
3056 }
3057 vholdl(vp);
3058 VI_UNLOCK(vp);
3059 cache_purge(vp);
3060 purged++;
3061 vdrop(vp);
3062 }
3063
3064 SDT_PROBE3(vfs, namecache, purgevfs, done, mp, visited, purged);
3065 }
3066
3067 /*
3068 * Perform canonical checks and cache lookup and pass on to filesystem
3069 * through the vop_cachedlookup only if needed.
3070 */
3071
3072 int
vfs_cache_lookup(struct vop_lookup_args * ap)3073 vfs_cache_lookup(struct vop_lookup_args *ap)
3074 {
3075 struct vnode *dvp;
3076 int error;
3077 struct vnode **vpp = ap->a_vpp;
3078 struct componentname *cnp = ap->a_cnp;
3079 int flags = cnp->cn_flags;
3080
3081 *vpp = NULL;
3082 dvp = ap->a_dvp;
3083
3084 if (dvp->v_type != VDIR)
3085 return (ENOTDIR);
3086
3087 if ((flags & ISLASTCN) && (dvp->v_mount->mnt_flag & MNT_RDONLY) &&
3088 (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME))
3089 return (EROFS);
3090
3091 error = vn_dir_check_exec(dvp, cnp);
3092 if (error != 0)
3093 return (error);
3094
3095 error = cache_lookup(dvp, vpp, cnp, NULL, NULL);
3096 if (error == 0)
3097 return (VOP_CACHEDLOOKUP(dvp, vpp, cnp));
3098 if (error == -1)
3099 return (0);
3100 return (error);
3101 }
3102
3103 /* Implementation of the getcwd syscall. */
3104 int
sys___getcwd(struct thread * td,struct __getcwd_args * uap)3105 sys___getcwd(struct thread *td, struct __getcwd_args *uap)
3106 {
3107 char *buf, *retbuf;
3108 size_t buflen;
3109 int error;
3110
3111 buflen = uap->buflen;
3112 if (__predict_false(buflen < 2))
3113 return (EINVAL);
3114 if (buflen > MAXPATHLEN)
3115 buflen = MAXPATHLEN;
3116
3117 buf = uma_zalloc(namei_zone, M_WAITOK);
3118 error = vn_getcwd(buf, &retbuf, &buflen);
3119 if (error == 0)
3120 error = copyout(retbuf, uap->buf, buflen);
3121 uma_zfree(namei_zone, buf);
3122 return (error);
3123 }
3124
3125 int
vn_getcwd(char * buf,char ** retbuf,size_t * buflen)3126 vn_getcwd(char *buf, char **retbuf, size_t *buflen)
3127 {
3128 struct pwd *pwd;
3129 int error;
3130
3131 vfs_smr_enter();
3132 pwd = pwd_get_smr();
3133 error = vn_fullpath_any_smr(pwd->pwd_cdir, pwd->pwd_rdir, buf, retbuf,
3134 buflen, 0);
3135 VFS_SMR_ASSERT_NOT_ENTERED();
3136 if (error < 0) {
3137 pwd = pwd_hold(curthread);
3138 error = vn_fullpath_any(pwd->pwd_cdir, pwd->pwd_rdir, buf,
3139 retbuf, buflen);
3140 pwd_drop(pwd);
3141 }
3142
3143 #ifdef KTRACE
3144 if (KTRPOINT(curthread, KTR_NAMEI) && error == 0)
3145 ktrnamei(*retbuf);
3146 #endif
3147 return (error);
3148 }
3149
3150 static int
kern___realpathat(struct thread * td,int fd,const char * path,char * buf,size_t size,int flags,enum uio_seg pathseg)3151 kern___realpathat(struct thread *td, int fd, const char *path, char *buf,
3152 size_t size, int flags, enum uio_seg pathseg)
3153 {
3154 struct nameidata nd;
3155 char *retbuf, *freebuf;
3156 int error;
3157
3158 if (flags != 0)
3159 return (EINVAL);
3160 NDINIT_ATRIGHTS(&nd, LOOKUP, FOLLOW | SAVENAME | WANTPARENT | AUDITVNODE1,
3161 pathseg, path, fd, &cap_fstat_rights, td);
3162 if ((error = namei(&nd)) != 0)
3163 return (error);
3164
3165 if (nd.ni_vp->v_type == VREG && nd.ni_dvp->v_type != VDIR &&
3166 (nd.ni_vp->v_vflag & VV_ROOT) != 0) {
3167 /*
3168 * This happens if vp is a file mount. The call to
3169 * vn_fullpath_hardlink can panic if path resolution can't be
3170 * handled without the directory.
3171 *
3172 * To resolve this, we find the vnode which was mounted on -
3173 * this should have a unique global path since we disallow
3174 * mounting on linked files.
3175 */
3176 struct vnode *covered_vp;
3177 error = vn_lock(nd.ni_vp, LK_SHARED);
3178 if (error != 0)
3179 goto out;
3180 covered_vp = nd.ni_vp->v_mount->mnt_vnodecovered;
3181 vref(covered_vp);
3182 VOP_UNLOCK(nd.ni_vp);
3183 error = vn_fullpath(covered_vp, &retbuf, &freebuf);
3184 vrele(covered_vp);
3185 } else {
3186 error = vn_fullpath_hardlink(nd.ni_vp, nd.ni_dvp, nd.ni_cnd.cn_nameptr,
3187 nd.ni_cnd.cn_namelen, &retbuf, &freebuf, &size);
3188 }
3189 if (error == 0) {
3190 error = copyout(retbuf, buf, size);
3191 free(freebuf, M_TEMP);
3192 }
3193 out:
3194 NDFREE(&nd, 0);
3195 return (error);
3196 }
3197
3198 int
sys___realpathat(struct thread * td,struct __realpathat_args * uap)3199 sys___realpathat(struct thread *td, struct __realpathat_args *uap)
3200 {
3201
3202 return (kern___realpathat(td, uap->fd, uap->path, uap->buf, uap->size,
3203 uap->flags, UIO_USERSPACE));
3204 }
3205
3206 /*
3207 * Retrieve the full filesystem path that correspond to a vnode from the name
3208 * cache (if available)
3209 */
3210 int
vn_fullpath(struct vnode * vp,char ** retbuf,char ** freebuf)3211 vn_fullpath(struct vnode *vp, char **retbuf, char **freebuf)
3212 {
3213 struct pwd *pwd;
3214 char *buf;
3215 size_t buflen;
3216 int error;
3217
3218 if (__predict_false(vp == NULL))
3219 return (EINVAL);
3220
3221 buflen = MAXPATHLEN;
3222 buf = malloc(buflen, M_TEMP, M_WAITOK);
3223 vfs_smr_enter();
3224 pwd = pwd_get_smr();
3225 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, &buflen, 0);
3226 VFS_SMR_ASSERT_NOT_ENTERED();
3227 if (error < 0) {
3228 pwd = pwd_hold(curthread);
3229 error = vn_fullpath_any(vp, pwd->pwd_rdir, buf, retbuf, &buflen);
3230 pwd_drop(pwd);
3231 }
3232 if (error == 0)
3233 *freebuf = buf;
3234 else
3235 free(buf, M_TEMP);
3236 return (error);
3237 }
3238
3239 /*
3240 * This function is similar to vn_fullpath, but it attempts to lookup the
3241 * pathname relative to the global root mount point. This is required for the
3242 * auditing sub-system, as audited pathnames must be absolute, relative to the
3243 * global root mount point.
3244 */
3245 int
vn_fullpath_global(struct vnode * vp,char ** retbuf,char ** freebuf)3246 vn_fullpath_global(struct vnode *vp, char **retbuf, char **freebuf)
3247 {
3248 char *buf;
3249 size_t buflen;
3250 int error;
3251
3252 if (__predict_false(vp == NULL))
3253 return (EINVAL);
3254 buflen = MAXPATHLEN;
3255 buf = malloc(buflen, M_TEMP, M_WAITOK);
3256 vfs_smr_enter();
3257 error = vn_fullpath_any_smr(vp, rootvnode, buf, retbuf, &buflen, 0);
3258 VFS_SMR_ASSERT_NOT_ENTERED();
3259 if (error < 0) {
3260 error = vn_fullpath_any(vp, rootvnode, buf, retbuf, &buflen);
3261 }
3262 if (error == 0)
3263 *freebuf = buf;
3264 else
3265 free(buf, M_TEMP);
3266 return (error);
3267 }
3268
3269 static struct namecache *
vn_dd_from_dst(struct vnode * vp)3270 vn_dd_from_dst(struct vnode *vp)
3271 {
3272 struct namecache *ncp;
3273
3274 cache_assert_vnode_locked(vp);
3275 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst) {
3276 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3277 return (ncp);
3278 }
3279 return (NULL);
3280 }
3281
3282 int
vn_vptocnp(struct vnode ** vp,char * buf,size_t * buflen)3283 vn_vptocnp(struct vnode **vp, char *buf, size_t *buflen)
3284 {
3285 struct vnode *dvp;
3286 struct namecache *ncp;
3287 struct mtx *vlp;
3288 int error;
3289
3290 vlp = VP2VNODELOCK(*vp);
3291 mtx_lock(vlp);
3292 ncp = (*vp)->v_cache_dd;
3293 if (ncp != NULL && (ncp->nc_flag & NCF_ISDOTDOT) == 0) {
3294 KASSERT(ncp == vn_dd_from_dst(*vp),
3295 ("%s: mismatch for dd entry (%p != %p)", __func__,
3296 ncp, vn_dd_from_dst(*vp)));
3297 } else {
3298 ncp = vn_dd_from_dst(*vp);
3299 }
3300 if (ncp != NULL) {
3301 if (*buflen < ncp->nc_nlen) {
3302 mtx_unlock(vlp);
3303 vrele(*vp);
3304 counter_u64_add(numfullpathfail4, 1);
3305 error = ENOMEM;
3306 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3307 vp, NULL);
3308 return (error);
3309 }
3310 *buflen -= ncp->nc_nlen;
3311 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3312 SDT_PROBE3(vfs, namecache, fullpath, hit, ncp->nc_dvp,
3313 ncp->nc_name, vp);
3314 dvp = *vp;
3315 *vp = ncp->nc_dvp;
3316 vref(*vp);
3317 mtx_unlock(vlp);
3318 vrele(dvp);
3319 return (0);
3320 }
3321 SDT_PROBE1(vfs, namecache, fullpath, miss, vp);
3322
3323 mtx_unlock(vlp);
3324 vn_lock(*vp, LK_SHARED | LK_RETRY);
3325 error = VOP_VPTOCNP(*vp, &dvp, buf, buflen);
3326 vput(*vp);
3327 if (error) {
3328 counter_u64_add(numfullpathfail2, 1);
3329 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3330 return (error);
3331 }
3332
3333 *vp = dvp;
3334 if (VN_IS_DOOMED(dvp)) {
3335 /* forced unmount */
3336 vrele(dvp);
3337 error = ENOENT;
3338 SDT_PROBE3(vfs, namecache, fullpath, return, error, vp, NULL);
3339 return (error);
3340 }
3341 /*
3342 * *vp has its use count incremented still.
3343 */
3344
3345 return (0);
3346 }
3347
3348 /*
3349 * Resolve a directory to a pathname.
3350 *
3351 * The name of the directory can always be found in the namecache or fetched
3352 * from the filesystem. There is also guaranteed to be only one parent, meaning
3353 * we can just follow vnodes up until we find the root.
3354 *
3355 * The vnode must be referenced.
3356 */
3357 static int
vn_fullpath_dir(struct vnode * vp,struct vnode * rdir,char * buf,char ** retbuf,size_t * len,size_t addend)3358 vn_fullpath_dir(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3359 size_t *len, size_t addend)
3360 {
3361 #ifdef KDTRACE_HOOKS
3362 struct vnode *startvp = vp;
3363 #endif
3364 struct vnode *vp1;
3365 size_t buflen;
3366 int error;
3367 bool slash_prefixed;
3368
3369 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3370 VNPASS(vp->v_usecount > 0, vp);
3371
3372 buflen = *len;
3373
3374 slash_prefixed = true;
3375 if (addend == 0) {
3376 MPASS(*len >= 2);
3377 buflen--;
3378 buf[buflen] = '\0';
3379 slash_prefixed = false;
3380 }
3381
3382 error = 0;
3383
3384 SDT_PROBE1(vfs, namecache, fullpath, entry, vp);
3385 counter_u64_add(numfullpathcalls, 1);
3386 while (vp != rdir && vp != rootvnode) {
3387 /*
3388 * The vp vnode must be already fully constructed,
3389 * since it is either found in namecache or obtained
3390 * from VOP_VPTOCNP(). We may test for VV_ROOT safely
3391 * without obtaining the vnode lock.
3392 */
3393 if ((vp->v_vflag & VV_ROOT) != 0) {
3394 vn_lock(vp, LK_RETRY | LK_SHARED);
3395
3396 /*
3397 * With the vnode locked, check for races with
3398 * unmount, forced or not. Note that we
3399 * already verified that vp is not equal to
3400 * the root vnode, which means that
3401 * mnt_vnodecovered can be NULL only for the
3402 * case of unmount.
3403 */
3404 if (VN_IS_DOOMED(vp) ||
3405 (vp1 = vp->v_mount->mnt_vnodecovered) == NULL ||
3406 vp1->v_mountedhere != vp->v_mount) {
3407 vput(vp);
3408 error = ENOENT;
3409 SDT_PROBE3(vfs, namecache, fullpath, return,
3410 error, vp, NULL);
3411 break;
3412 }
3413
3414 vref(vp1);
3415 vput(vp);
3416 vp = vp1;
3417 continue;
3418 }
3419 VNPASS(vp->v_type == VDIR || VN_IS_DOOMED(vp), vp);
3420 error = vn_vptocnp(&vp, buf, &buflen);
3421 if (error)
3422 break;
3423 if (buflen == 0) {
3424 vrele(vp);
3425 error = ENOMEM;
3426 SDT_PROBE3(vfs, namecache, fullpath, return, error,
3427 startvp, NULL);
3428 break;
3429 }
3430 buf[--buflen] = '/';
3431 slash_prefixed = true;
3432 }
3433 if (error)
3434 return (error);
3435 if (!slash_prefixed) {
3436 if (buflen == 0) {
3437 vrele(vp);
3438 counter_u64_add(numfullpathfail4, 1);
3439 SDT_PROBE3(vfs, namecache, fullpath, return, ENOMEM,
3440 startvp, NULL);
3441 return (ENOMEM);
3442 }
3443 buf[--buflen] = '/';
3444 }
3445 counter_u64_add(numfullpathfound, 1);
3446 vrele(vp);
3447
3448 *retbuf = buf + buflen;
3449 SDT_PROBE3(vfs, namecache, fullpath, return, 0, startvp, *retbuf);
3450 *len -= buflen;
3451 *len += addend;
3452 return (0);
3453 }
3454
3455 /*
3456 * Resolve an arbitrary vnode to a pathname.
3457 *
3458 * Note 2 caveats:
3459 * - hardlinks are not tracked, thus if the vnode is not a directory this can
3460 * resolve to a different path than the one used to find it
3461 * - namecache is not mandatory, meaning names are not guaranteed to be added
3462 * (in which case resolving fails)
3463 */
3464 static void __inline
cache_rev_failed_impl(int * reason,int line)3465 cache_rev_failed_impl(int *reason, int line)
3466 {
3467
3468 *reason = line;
3469 }
3470 #define cache_rev_failed(var) cache_rev_failed_impl((var), __LINE__)
3471
3472 static int
vn_fullpath_any_smr(struct vnode * vp,struct vnode * rdir,char * buf,char ** retbuf,size_t * buflen,size_t addend)3473 vn_fullpath_any_smr(struct vnode *vp, struct vnode *rdir, char *buf,
3474 char **retbuf, size_t *buflen, size_t addend)
3475 {
3476 #ifdef KDTRACE_HOOKS
3477 struct vnode *startvp = vp;
3478 #endif
3479 struct vnode *tvp;
3480 struct mount *mp;
3481 struct namecache *ncp;
3482 size_t orig_buflen;
3483 int reason;
3484 int error;
3485 #ifdef KDTRACE_HOOKS
3486 int i;
3487 #endif
3488 seqc_t vp_seqc, tvp_seqc;
3489 u_char nc_flag;
3490
3491 VFS_SMR_ASSERT_ENTERED();
3492
3493 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
3494 vfs_smr_exit();
3495 return (-1);
3496 }
3497
3498 orig_buflen = *buflen;
3499
3500 if (addend == 0) {
3501 MPASS(*buflen >= 2);
3502 *buflen -= 1;
3503 buf[*buflen] = '\0';
3504 }
3505
3506 if (vp == rdir || vp == rootvnode) {
3507 if (addend == 0) {
3508 *buflen -= 1;
3509 buf[*buflen] = '/';
3510 }
3511 goto out_ok;
3512 }
3513
3514 #ifdef KDTRACE_HOOKS
3515 i = 0;
3516 #endif
3517 error = -1;
3518 ncp = NULL; /* for sdt probe down below */
3519 vp_seqc = vn_seqc_read_any(vp);
3520 if (seqc_in_modify(vp_seqc)) {
3521 cache_rev_failed(&reason);
3522 goto out_abort;
3523 }
3524
3525 for (;;) {
3526 #ifdef KDTRACE_HOOKS
3527 i++;
3528 #endif
3529 if ((vp->v_vflag & VV_ROOT) != 0) {
3530 mp = atomic_load_ptr(&vp->v_mount);
3531 if (mp == NULL) {
3532 cache_rev_failed(&reason);
3533 goto out_abort;
3534 }
3535 tvp = atomic_load_ptr(&mp->mnt_vnodecovered);
3536 tvp_seqc = vn_seqc_read_any(tvp);
3537 if (seqc_in_modify(tvp_seqc)) {
3538 cache_rev_failed(&reason);
3539 goto out_abort;
3540 }
3541 if (!vn_seqc_consistent(vp, vp_seqc)) {
3542 cache_rev_failed(&reason);
3543 goto out_abort;
3544 }
3545 vp = tvp;
3546 vp_seqc = tvp_seqc;
3547 continue;
3548 }
3549 ncp = atomic_load_consume_ptr(&vp->v_cache_dd);
3550 if (ncp == NULL) {
3551 cache_rev_failed(&reason);
3552 goto out_abort;
3553 }
3554 nc_flag = atomic_load_char(&ncp->nc_flag);
3555 if ((nc_flag & NCF_ISDOTDOT) != 0) {
3556 cache_rev_failed(&reason);
3557 goto out_abort;
3558 }
3559 if (ncp->nc_nlen >= *buflen) {
3560 cache_rev_failed(&reason);
3561 error = ENOMEM;
3562 goto out_abort;
3563 }
3564 *buflen -= ncp->nc_nlen;
3565 memcpy(buf + *buflen, ncp->nc_name, ncp->nc_nlen);
3566 *buflen -= 1;
3567 buf[*buflen] = '/';
3568 tvp = ncp->nc_dvp;
3569 tvp_seqc = vn_seqc_read_any(tvp);
3570 if (seqc_in_modify(tvp_seqc)) {
3571 cache_rev_failed(&reason);
3572 goto out_abort;
3573 }
3574 if (!vn_seqc_consistent(vp, vp_seqc)) {
3575 cache_rev_failed(&reason);
3576 goto out_abort;
3577 }
3578 /*
3579 * Acquire fence provided by vn_seqc_read_any above.
3580 */
3581 if (__predict_false(atomic_load_ptr(&vp->v_cache_dd) != ncp)) {
3582 cache_rev_failed(&reason);
3583 goto out_abort;
3584 }
3585 if (!cache_ncp_canuse(ncp)) {
3586 cache_rev_failed(&reason);
3587 goto out_abort;
3588 }
3589 vp = tvp;
3590 vp_seqc = tvp_seqc;
3591 if (vp == rdir || vp == rootvnode)
3592 break;
3593 }
3594 out_ok:
3595 vfs_smr_exit();
3596 *retbuf = buf + *buflen;
3597 *buflen = orig_buflen - *buflen + addend;
3598 SDT_PROBE2(vfs, namecache, fullpath_smr, hit, startvp, *retbuf);
3599 return (0);
3600
3601 out_abort:
3602 *buflen = orig_buflen;
3603 SDT_PROBE4(vfs, namecache, fullpath_smr, miss, startvp, ncp, reason, i);
3604 vfs_smr_exit();
3605 return (error);
3606 }
3607
3608 static int
vn_fullpath_any(struct vnode * vp,struct vnode * rdir,char * buf,char ** retbuf,size_t * buflen)3609 vn_fullpath_any(struct vnode *vp, struct vnode *rdir, char *buf, char **retbuf,
3610 size_t *buflen)
3611 {
3612 size_t orig_buflen, addend;
3613 int error;
3614
3615 if (*buflen < 2)
3616 return (EINVAL);
3617
3618 orig_buflen = *buflen;
3619
3620 vref(vp);
3621 addend = 0;
3622 if (vp->v_type != VDIR) {
3623 *buflen -= 1;
3624 buf[*buflen] = '\0';
3625 error = vn_vptocnp(&vp, buf, buflen);
3626 if (error)
3627 return (error);
3628 if (*buflen == 0) {
3629 vrele(vp);
3630 return (ENOMEM);
3631 }
3632 *buflen -= 1;
3633 buf[*buflen] = '/';
3634 addend = orig_buflen - *buflen;
3635 }
3636
3637 return (vn_fullpath_dir(vp, rdir, buf, retbuf, buflen, addend));
3638 }
3639
3640 /*
3641 * Resolve an arbitrary vnode to a pathname (taking care of hardlinks).
3642 *
3643 * Since the namecache does not track hardlinks, the caller is
3644 * expected to first look up the target vnode with SAVENAME |
3645 * WANTPARENT flags passed to namei to get dvp and vp.
3646 *
3647 * Then we have 2 cases:
3648 * - if the found vnode is a directory, the path can be constructed just by
3649 * following names up the chain
3650 * - otherwise we populate the buffer with the saved name and start resolving
3651 * from the parent
3652 */
3653 int
vn_fullpath_hardlink(struct vnode * vp,struct vnode * dvp,const char * hrdl_name,size_t hrdl_name_length,char ** retbuf,char ** freebuf,size_t * buflen)3654 vn_fullpath_hardlink(struct vnode *vp, struct vnode *dvp,
3655 const char *hrdl_name, size_t hrdl_name_length,
3656 char **retbuf, char **freebuf, size_t *buflen)
3657 {
3658 char *buf, *tmpbuf;
3659 struct pwd *pwd;
3660 size_t addend;
3661 int error;
3662 enum vtype type;
3663
3664 if (*buflen < 2)
3665 return (EINVAL);
3666 if (*buflen > MAXPATHLEN)
3667 *buflen = MAXPATHLEN;
3668
3669 buf = malloc(*buflen, M_TEMP, M_WAITOK);
3670
3671 addend = 0;
3672
3673 /*
3674 * Check for VBAD to work around the vp_crossmp bug in lookup().
3675 *
3676 * For example consider tmpfs on /tmp and realpath /tmp. ni_vp will be
3677 * set to mount point's root vnode while ni_dvp will be vp_crossmp.
3678 * If the type is VDIR (like in this very case) we can skip looking
3679 * at ni_dvp in the first place. However, since vnodes get passed here
3680 * unlocked the target may transition to doomed state (type == VBAD)
3681 * before we get to evaluate the condition. If this happens, we will
3682 * populate part of the buffer and descend to vn_fullpath_dir with
3683 * vp == vp_crossmp. Prevent the problem by checking for VBAD.
3684 *
3685 * This should be atomic_load(&vp->v_type) but it is illegal to take
3686 * an address of a bit field, even if said field is sized to char.
3687 * Work around the problem by reading the value into a full-sized enum
3688 * and then re-reading it with atomic_load which will still prevent
3689 * the compiler from re-reading down the road.
3690 */
3691 type = vp->v_type;
3692 type = atomic_load_int(&type);
3693 if (type == VBAD) {
3694 error = ENOENT;
3695 goto out_bad;
3696 }
3697 if (type != VDIR) {
3698 addend = hrdl_name_length + 2;
3699 if (*buflen < addend) {
3700 error = ENOMEM;
3701 goto out_bad;
3702 }
3703 *buflen -= addend;
3704 tmpbuf = buf + *buflen;
3705 tmpbuf[0] = '/';
3706 memcpy(&tmpbuf[1], hrdl_name, hrdl_name_length);
3707 tmpbuf[addend - 1] = '\0';
3708 vp = dvp;
3709 }
3710
3711 vfs_smr_enter();
3712 pwd = pwd_get_smr();
3713 error = vn_fullpath_any_smr(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3714 addend);
3715 VFS_SMR_ASSERT_NOT_ENTERED();
3716 if (error < 0) {
3717 pwd = pwd_hold(curthread);
3718 vref(vp);
3719 error = vn_fullpath_dir(vp, pwd->pwd_rdir, buf, retbuf, buflen,
3720 addend);
3721 pwd_drop(pwd);
3722 }
3723 if (error != 0)
3724 goto out_bad;
3725
3726 *freebuf = buf;
3727
3728 return (0);
3729 out_bad:
3730 free(buf, M_TEMP);
3731 return (error);
3732 }
3733
3734 struct vnode *
vn_dir_dd_ino(struct vnode * vp)3735 vn_dir_dd_ino(struct vnode *vp)
3736 {
3737 struct namecache *ncp;
3738 struct vnode *ddvp;
3739 struct mtx *vlp;
3740 enum vgetstate vs;
3741
3742 ASSERT_VOP_LOCKED(vp, "vn_dir_dd_ino");
3743 vlp = VP2VNODELOCK(vp);
3744 mtx_lock(vlp);
3745 TAILQ_FOREACH(ncp, &(vp->v_cache_dst), nc_dst) {
3746 if ((ncp->nc_flag & NCF_ISDOTDOT) != 0)
3747 continue;
3748 ddvp = ncp->nc_dvp;
3749 vs = vget_prep(ddvp);
3750 mtx_unlock(vlp);
3751 if (vget_finish(ddvp, LK_SHARED | LK_NOWAIT, vs))
3752 return (NULL);
3753 return (ddvp);
3754 }
3755 mtx_unlock(vlp);
3756 return (NULL);
3757 }
3758
3759 int
vn_commname(struct vnode * vp,char * buf,u_int buflen)3760 vn_commname(struct vnode *vp, char *buf, u_int buflen)
3761 {
3762 struct namecache *ncp;
3763 struct mtx *vlp;
3764 int l;
3765
3766 vlp = VP2VNODELOCK(vp);
3767 mtx_lock(vlp);
3768 TAILQ_FOREACH(ncp, &vp->v_cache_dst, nc_dst)
3769 if ((ncp->nc_flag & NCF_ISDOTDOT) == 0)
3770 break;
3771 if (ncp == NULL) {
3772 mtx_unlock(vlp);
3773 return (ENOENT);
3774 }
3775 l = min(ncp->nc_nlen, buflen - 1);
3776 memcpy(buf, ncp->nc_name, l);
3777 mtx_unlock(vlp);
3778 buf[l] = '\0';
3779 return (0);
3780 }
3781
3782 /*
3783 * This function updates path string to vnode's full global path
3784 * and checks the size of the new path string against the pathlen argument.
3785 *
3786 * Requires a locked, referenced vnode.
3787 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3788 *
3789 * If vp is a directory, the call to vn_fullpath_global() always succeeds
3790 * because it falls back to the ".." lookup if the namecache lookup fails.
3791 */
3792 int
vn_path_to_global_path(struct thread * td,struct vnode * vp,char * path,u_int pathlen)3793 vn_path_to_global_path(struct thread *td, struct vnode *vp, char *path,
3794 u_int pathlen)
3795 {
3796 struct nameidata nd;
3797 struct vnode *vp1;
3798 char *rpath, *fbuf;
3799 int error;
3800
3801 ASSERT_VOP_ELOCKED(vp, __func__);
3802
3803 /* Construct global filesystem path from vp. */
3804 VOP_UNLOCK(vp);
3805 error = vn_fullpath_global(vp, &rpath, &fbuf);
3806
3807 if (error != 0) {
3808 vrele(vp);
3809 return (error);
3810 }
3811
3812 if (strlen(rpath) >= pathlen) {
3813 vrele(vp);
3814 error = ENAMETOOLONG;
3815 goto out;
3816 }
3817
3818 /*
3819 * Re-lookup the vnode by path to detect a possible rename.
3820 * As a side effect, the vnode is relocked.
3821 * If vnode was renamed, return ENOENT.
3822 */
3823 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1,
3824 UIO_SYSSPACE, path, td);
3825 error = namei(&nd);
3826 if (error != 0) {
3827 vrele(vp);
3828 goto out;
3829 }
3830 NDFREE(&nd, NDF_ONLY_PNBUF);
3831 vp1 = nd.ni_vp;
3832 vrele(vp);
3833 if (vp1 == vp)
3834 strcpy(path, rpath);
3835 else {
3836 vput(vp1);
3837 error = ENOENT;
3838 }
3839
3840 out:
3841 free(fbuf, M_TEMP);
3842 return (error);
3843 }
3844
3845 /*
3846 * This is similar to vn_path_to_global_path but allows for regular
3847 * files which may not be present in the cache.
3848 *
3849 * Requires a locked, referenced vnode.
3850 * Vnode is re-locked on success or ENODEV, otherwise unlocked.
3851 */
3852 int
vn_path_to_global_path_hardlink(struct thread * td,struct vnode * vp,struct vnode * dvp,char * path,u_int pathlen,const char * leaf_name,size_t leaf_length)3853 vn_path_to_global_path_hardlink(struct thread *td, struct vnode *vp,
3854 struct vnode *dvp, char *path, u_int pathlen, const char *leaf_name,
3855 size_t leaf_length)
3856 {
3857 struct nameidata nd;
3858 struct vnode *vp1;
3859 char *rpath, *fbuf;
3860 size_t len;
3861 int error;
3862
3863 ASSERT_VOP_ELOCKED(vp, __func__);
3864
3865 /*
3866 * Construct global filesystem path from dvp, vp and leaf
3867 * name.
3868 */
3869 VOP_UNLOCK(vp);
3870 len = pathlen;
3871 error = vn_fullpath_hardlink(vp, dvp, leaf_name, leaf_length,
3872 &rpath, &fbuf, &len);
3873
3874 if (error != 0) {
3875 vrele(vp);
3876 return (error);
3877 }
3878
3879 if (strlen(rpath) >= pathlen) {
3880 vrele(vp);
3881 error = ENAMETOOLONG;
3882 goto out;
3883 }
3884
3885 /*
3886 * Re-lookup the vnode by path to detect a possible rename.
3887 * As a side effect, the vnode is relocked.
3888 * If vnode was renamed, return ENOENT.
3889 */
3890 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | AUDITVNODE1, UIO_SYSSPACE, path, td);
3891 error = namei(&nd);
3892 if (error != 0) {
3893 vrele(vp);
3894 goto out;
3895 }
3896 NDFREE_PNBUF(&nd);
3897 vp1 = nd.ni_vp;
3898 vrele(vp);
3899 if (vp1 == vp)
3900 strcpy(path, rpath);
3901 else {
3902 vput(vp1);
3903 error = ENOENT;
3904 }
3905
3906 out:
3907 free(fbuf, M_TEMP);
3908 return (error);
3909 }
3910
3911 #ifdef DDB
3912 static void
db_print_vpath(struct vnode * vp)3913 db_print_vpath(struct vnode *vp)
3914 {
3915
3916 while (vp != NULL) {
3917 db_printf("%p: ", vp);
3918 if (vp == rootvnode) {
3919 db_printf("/");
3920 vp = NULL;
3921 } else {
3922 if (vp->v_vflag & VV_ROOT) {
3923 db_printf("<mount point>");
3924 vp = vp->v_mount->mnt_vnodecovered;
3925 } else {
3926 struct namecache *ncp;
3927 char *ncn;
3928 int i;
3929
3930 ncp = TAILQ_FIRST(&vp->v_cache_dst);
3931 if (ncp != NULL) {
3932 ncn = ncp->nc_name;
3933 for (i = 0; i < ncp->nc_nlen; i++)
3934 db_printf("%c", *ncn++);
3935 vp = ncp->nc_dvp;
3936 } else {
3937 vp = NULL;
3938 }
3939 }
3940 }
3941 db_printf("\n");
3942 }
3943
3944 return;
3945 }
3946
DB_SHOW_COMMAND(vpath,db_show_vpath)3947 DB_SHOW_COMMAND(vpath, db_show_vpath)
3948 {
3949 struct vnode *vp;
3950
3951 if (!have_addr) {
3952 db_printf("usage: show vpath <struct vnode *>\n");
3953 return;
3954 }
3955
3956 vp = (struct vnode *)addr;
3957 db_print_vpath(vp);
3958 }
3959
3960 #endif
3961
3962 static int cache_fast_lookup = 1;
3963
3964 #define CACHE_FPL_FAILED -2020
3965
3966 void
cache_fast_lookup_enabled_recalc(void)3967 cache_fast_lookup_enabled_recalc(void)
3968 {
3969 int lookup_flag;
3970 int mac_on;
3971
3972 #ifdef MAC
3973 mac_on = mac_vnode_check_lookup_enabled();
3974 mac_on |= mac_vnode_check_readlink_enabled();
3975 #else
3976 mac_on = 0;
3977 #endif
3978
3979 lookup_flag = atomic_load_int(&cache_fast_lookup);
3980 if (lookup_flag && !mac_on) {
3981 atomic_store_char(&cache_fast_lookup_enabled, true);
3982 } else {
3983 atomic_store_char(&cache_fast_lookup_enabled, false);
3984 }
3985 }
3986
3987 static int
syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)3988 syscal_vfs_cache_fast_lookup(SYSCTL_HANDLER_ARGS)
3989 {
3990 int error, old;
3991
3992 old = atomic_load_int(&cache_fast_lookup);
3993 error = sysctl_handle_int(oidp, arg1, arg2, req);
3994 if (error == 0 && req->newptr && old != atomic_load_int(&cache_fast_lookup))
3995 cache_fast_lookup_enabled_recalc();
3996 return (error);
3997 }
3998 SYSCTL_PROC(_vfs, OID_AUTO, cache_fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
3999 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
4000 SYSCTL_PROC(_vfs_cache_param, OID_AUTO, fast_lookup, CTLTYPE_INT|CTLFLAG_RW|CTLFLAG_MPSAFE,
4001 &cache_fast_lookup, 0, syscal_vfs_cache_fast_lookup, "IU", "");
4002
4003 /*
4004 * Components of nameidata (or objects it can point to) which may
4005 * need restoring in case fast path lookup fails.
4006 */
4007 struct nameidata_outer {
4008 size_t ni_pathlen;
4009 int cn_flags;
4010 };
4011
4012 struct nameidata_saved {
4013 #ifdef INVARIANTS
4014 char *cn_nameptr;
4015 size_t ni_pathlen;
4016 #endif
4017 };
4018
4019 #ifdef INVARIANTS
4020 struct cache_fpl_debug {
4021 size_t ni_pathlen;
4022 };
4023 #endif
4024
4025 struct cache_fpl {
4026 struct nameidata *ndp;
4027 struct componentname *cnp;
4028 char *nulchar;
4029 struct vnode *dvp;
4030 struct vnode *tvp;
4031 seqc_t dvp_seqc;
4032 seqc_t tvp_seqc;
4033 uint32_t hash;
4034 struct nameidata_saved snd;
4035 struct nameidata_outer snd_outer;
4036 int line;
4037 enum cache_fpl_status status:8;
4038 bool in_smr;
4039 bool fsearch;
4040 bool savename;
4041 struct pwd **pwd;
4042 #ifdef INVARIANTS
4043 struct cache_fpl_debug debug;
4044 #endif
4045 };
4046
4047 static bool cache_fplookup_mp_supported(struct mount *mp);
4048 static bool cache_fplookup_is_mp(struct cache_fpl *fpl);
4049 static int cache_fplookup_cross_mount(struct cache_fpl *fpl);
4050 static int cache_fplookup_partial_setup(struct cache_fpl *fpl);
4051 static int cache_fplookup_skip_slashes(struct cache_fpl *fpl);
4052 static int cache_fplookup_trailingslash(struct cache_fpl *fpl);
4053 static void cache_fpl_pathlen_dec(struct cache_fpl *fpl);
4054 static void cache_fpl_pathlen_inc(struct cache_fpl *fpl);
4055 static void cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n);
4056 static void cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n);
4057
4058 static void
cache_fpl_cleanup_cnp(struct componentname * cnp)4059 cache_fpl_cleanup_cnp(struct componentname *cnp)
4060 {
4061
4062 uma_zfree(namei_zone, cnp->cn_pnbuf);
4063 #ifdef DIAGNOSTIC
4064 cnp->cn_pnbuf = NULL;
4065 cnp->cn_nameptr = NULL;
4066 #endif
4067 }
4068
4069 static struct vnode *
cache_fpl_handle_root(struct cache_fpl * fpl)4070 cache_fpl_handle_root(struct cache_fpl *fpl)
4071 {
4072 struct nameidata *ndp;
4073 struct componentname *cnp;
4074
4075 ndp = fpl->ndp;
4076 cnp = fpl->cnp;
4077
4078 MPASS(*(cnp->cn_nameptr) == '/');
4079 cnp->cn_nameptr++;
4080 cache_fpl_pathlen_dec(fpl);
4081
4082 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4083 do {
4084 cnp->cn_nameptr++;
4085 cache_fpl_pathlen_dec(fpl);
4086 } while (*(cnp->cn_nameptr) == '/');
4087 }
4088
4089 return (ndp->ni_rootdir);
4090 }
4091
4092 static void
cache_fpl_checkpoint_outer(struct cache_fpl * fpl)4093 cache_fpl_checkpoint_outer(struct cache_fpl *fpl)
4094 {
4095
4096 fpl->snd_outer.ni_pathlen = fpl->ndp->ni_pathlen;
4097 fpl->snd_outer.cn_flags = fpl->ndp->ni_cnd.cn_flags;
4098 }
4099
4100 static void
cache_fpl_checkpoint(struct cache_fpl * fpl)4101 cache_fpl_checkpoint(struct cache_fpl *fpl)
4102 {
4103
4104 #ifdef INVARIANTS
4105 fpl->snd.cn_nameptr = fpl->ndp->ni_cnd.cn_nameptr;
4106 fpl->snd.ni_pathlen = fpl->debug.ni_pathlen;
4107 #endif
4108 }
4109
4110 static void
cache_fpl_restore_partial(struct cache_fpl * fpl)4111 cache_fpl_restore_partial(struct cache_fpl *fpl)
4112 {
4113
4114 fpl->ndp->ni_cnd.cn_flags = fpl->snd_outer.cn_flags;
4115 #ifdef INVARIANTS
4116 fpl->debug.ni_pathlen = fpl->snd.ni_pathlen;
4117 #endif
4118 }
4119
4120 static void
cache_fpl_restore_abort(struct cache_fpl * fpl)4121 cache_fpl_restore_abort(struct cache_fpl *fpl)
4122 {
4123
4124 cache_fpl_restore_partial(fpl);
4125 /*
4126 * It is 0 on entry by API contract.
4127 */
4128 fpl->ndp->ni_resflags = 0;
4129 fpl->ndp->ni_cnd.cn_nameptr = fpl->ndp->ni_cnd.cn_pnbuf;
4130 fpl->ndp->ni_pathlen = fpl->snd_outer.ni_pathlen;
4131 }
4132
4133 #ifdef INVARIANTS
4134 #define cache_fpl_smr_assert_entered(fpl) ({ \
4135 struct cache_fpl *_fpl = (fpl); \
4136 MPASS(_fpl->in_smr == true); \
4137 VFS_SMR_ASSERT_ENTERED(); \
4138 })
4139 #define cache_fpl_smr_assert_not_entered(fpl) ({ \
4140 struct cache_fpl *_fpl = (fpl); \
4141 MPASS(_fpl->in_smr == false); \
4142 VFS_SMR_ASSERT_NOT_ENTERED(); \
4143 })
4144 static void
cache_fpl_assert_status(struct cache_fpl * fpl)4145 cache_fpl_assert_status(struct cache_fpl *fpl)
4146 {
4147
4148 switch (fpl->status) {
4149 case CACHE_FPL_STATUS_UNSET:
4150 __assert_unreachable();
4151 break;
4152 case CACHE_FPL_STATUS_DESTROYED:
4153 case CACHE_FPL_STATUS_ABORTED:
4154 case CACHE_FPL_STATUS_PARTIAL:
4155 case CACHE_FPL_STATUS_HANDLED:
4156 break;
4157 }
4158 }
4159 #else
4160 #define cache_fpl_smr_assert_entered(fpl) do { } while (0)
4161 #define cache_fpl_smr_assert_not_entered(fpl) do { } while (0)
4162 #define cache_fpl_assert_status(fpl) do { } while (0)
4163 #endif
4164
4165 #define cache_fpl_smr_enter_initial(fpl) ({ \
4166 struct cache_fpl *_fpl = (fpl); \
4167 vfs_smr_enter(); \
4168 _fpl->in_smr = true; \
4169 })
4170
4171 #define cache_fpl_smr_enter(fpl) ({ \
4172 struct cache_fpl *_fpl = (fpl); \
4173 MPASS(_fpl->in_smr == false); \
4174 vfs_smr_enter(); \
4175 _fpl->in_smr = true; \
4176 })
4177
4178 #define cache_fpl_smr_exit(fpl) ({ \
4179 struct cache_fpl *_fpl = (fpl); \
4180 MPASS(_fpl->in_smr == true); \
4181 vfs_smr_exit(); \
4182 _fpl->in_smr = false; \
4183 })
4184
4185 static int
cache_fpl_aborted_early_impl(struct cache_fpl * fpl,int line)4186 cache_fpl_aborted_early_impl(struct cache_fpl *fpl, int line)
4187 {
4188
4189 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4190 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4191 ("%s: converting to abort from %d at %d, set at %d\n",
4192 __func__, fpl->status, line, fpl->line));
4193 }
4194 cache_fpl_smr_assert_not_entered(fpl);
4195 fpl->status = CACHE_FPL_STATUS_ABORTED;
4196 fpl->line = line;
4197 return (CACHE_FPL_FAILED);
4198 }
4199
4200 #define cache_fpl_aborted_early(x) cache_fpl_aborted_early_impl((x), __LINE__)
4201
4202 static int __noinline
cache_fpl_aborted_impl(struct cache_fpl * fpl,int line)4203 cache_fpl_aborted_impl(struct cache_fpl *fpl, int line)
4204 {
4205 struct nameidata *ndp;
4206 struct componentname *cnp;
4207
4208 ndp = fpl->ndp;
4209 cnp = fpl->cnp;
4210
4211 if (fpl->status != CACHE_FPL_STATUS_UNSET) {
4212 KASSERT(fpl->status == CACHE_FPL_STATUS_PARTIAL,
4213 ("%s: converting to abort from %d at %d, set at %d\n",
4214 __func__, fpl->status, line, fpl->line));
4215 }
4216 fpl->status = CACHE_FPL_STATUS_ABORTED;
4217 fpl->line = line;
4218 if (fpl->in_smr)
4219 cache_fpl_smr_exit(fpl);
4220 cache_fpl_restore_abort(fpl);
4221 /*
4222 * Resolving symlinks overwrites data passed by the caller.
4223 * Let namei know.
4224 */
4225 if (ndp->ni_loopcnt > 0) {
4226 fpl->status = CACHE_FPL_STATUS_DESTROYED;
4227 cache_fpl_cleanup_cnp(cnp);
4228 }
4229 return (CACHE_FPL_FAILED);
4230 }
4231
4232 #define cache_fpl_aborted(x) cache_fpl_aborted_impl((x), __LINE__)
4233
4234 static int __noinline
cache_fpl_partial_impl(struct cache_fpl * fpl,int line)4235 cache_fpl_partial_impl(struct cache_fpl *fpl, int line)
4236 {
4237
4238 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4239 ("%s: setting to partial at %d, but already set to %d at %d\n",
4240 __func__, line, fpl->status, fpl->line));
4241 cache_fpl_smr_assert_entered(fpl);
4242 fpl->status = CACHE_FPL_STATUS_PARTIAL;
4243 fpl->line = line;
4244 return (cache_fplookup_partial_setup(fpl));
4245 }
4246
4247 #define cache_fpl_partial(x) cache_fpl_partial_impl((x), __LINE__)
4248
4249 static int
cache_fpl_handled_impl(struct cache_fpl * fpl,int line)4250 cache_fpl_handled_impl(struct cache_fpl *fpl, int line)
4251 {
4252
4253 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4254 ("%s: setting to handled at %d, but already set to %d at %d\n",
4255 __func__, line, fpl->status, fpl->line));
4256 cache_fpl_smr_assert_not_entered(fpl);
4257 fpl->status = CACHE_FPL_STATUS_HANDLED;
4258 fpl->line = line;
4259 return (0);
4260 }
4261
4262 #define cache_fpl_handled(x) cache_fpl_handled_impl((x), __LINE__)
4263
4264 static int
cache_fpl_handled_error_impl(struct cache_fpl * fpl,int error,int line)4265 cache_fpl_handled_error_impl(struct cache_fpl *fpl, int error, int line)
4266 {
4267
4268 KASSERT(fpl->status == CACHE_FPL_STATUS_UNSET,
4269 ("%s: setting to handled at %d, but already set to %d at %d\n",
4270 __func__, line, fpl->status, fpl->line));
4271 MPASS(error != 0);
4272 MPASS(error != CACHE_FPL_FAILED);
4273 cache_fpl_smr_assert_not_entered(fpl);
4274 fpl->status = CACHE_FPL_STATUS_HANDLED;
4275 fpl->line = line;
4276 fpl->dvp = NULL;
4277 fpl->tvp = NULL;
4278 fpl->savename = false;
4279 return (error);
4280 }
4281
4282 #define cache_fpl_handled_error(x, e) cache_fpl_handled_error_impl((x), (e), __LINE__)
4283
4284 static bool
cache_fpl_terminated(struct cache_fpl * fpl)4285 cache_fpl_terminated(struct cache_fpl *fpl)
4286 {
4287
4288 return (fpl->status != CACHE_FPL_STATUS_UNSET);
4289 }
4290
4291 #define CACHE_FPL_SUPPORTED_CN_FLAGS \
4292 (NC_NOMAKEENTRY | NC_KEEPPOSENTRY | LOCKLEAF | LOCKPARENT | WANTPARENT | \
4293 FAILIFEXISTS | FOLLOW | EMPTYPATH | LOCKSHARED | SAVENAME | SAVESTART | \
4294 WILLBEDIR | ISOPEN | NOMACCHECK | AUDITVNODE1 | AUDITVNODE2 | NOCAPCHECK | \
4295 WANTIOCTLCAPS)
4296
4297 #define CACHE_FPL_INTERNAL_CN_FLAGS \
4298 (ISDOTDOT | MAKEENTRY | ISLASTCN)
4299
4300 _Static_assert((CACHE_FPL_SUPPORTED_CN_FLAGS & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
4301 "supported and internal flags overlap");
4302
4303 static bool
cache_fpl_islastcn(struct nameidata * ndp)4304 cache_fpl_islastcn(struct nameidata *ndp)
4305 {
4306
4307 return (*ndp->ni_next == 0);
4308 }
4309
4310 static bool
cache_fpl_istrailingslash(struct cache_fpl * fpl)4311 cache_fpl_istrailingslash(struct cache_fpl *fpl)
4312 {
4313
4314 MPASS(fpl->nulchar > fpl->cnp->cn_pnbuf);
4315 return (*(fpl->nulchar - 1) == '/');
4316 }
4317
4318 static bool
cache_fpl_isdotdot(struct componentname * cnp)4319 cache_fpl_isdotdot(struct componentname *cnp)
4320 {
4321
4322 if (cnp->cn_namelen == 2 &&
4323 cnp->cn_nameptr[1] == '.' && cnp->cn_nameptr[0] == '.')
4324 return (true);
4325 return (false);
4326 }
4327
4328 static bool
cache_can_fplookup(struct cache_fpl * fpl)4329 cache_can_fplookup(struct cache_fpl *fpl)
4330 {
4331 struct nameidata *ndp;
4332 struct componentname *cnp;
4333 struct thread *td;
4334
4335 ndp = fpl->ndp;
4336 cnp = fpl->cnp;
4337 td = cnp->cn_thread;
4338
4339 if (!atomic_load_char(&cache_fast_lookup_enabled)) {
4340 cache_fpl_aborted_early(fpl);
4341 return (false);
4342 }
4343 if ((cnp->cn_flags & ~CACHE_FPL_SUPPORTED_CN_FLAGS) != 0) {
4344 cache_fpl_aborted_early(fpl);
4345 return (false);
4346 }
4347 if (IN_CAPABILITY_MODE(td)) {
4348 cache_fpl_aborted_early(fpl);
4349 return (false);
4350 }
4351 if (AUDITING_TD(td)) {
4352 cache_fpl_aborted_early(fpl);
4353 return (false);
4354 }
4355 if (ndp->ni_startdir != NULL) {
4356 cache_fpl_aborted_early(fpl);
4357 return (false);
4358 }
4359 return (true);
4360 }
4361
4362 static int __noinline
cache_fplookup_dirfd(struct cache_fpl * fpl,struct vnode ** vpp)4363 cache_fplookup_dirfd(struct cache_fpl *fpl, struct vnode **vpp)
4364 {
4365 struct nameidata *ndp;
4366 struct componentname *cnp;
4367 int error;
4368 bool fsearch;
4369
4370 ndp = fpl->ndp;
4371 cnp = fpl->cnp;
4372
4373 error = fgetvp_lookup_smr(ndp->ni_dirfd, ndp, vpp, &fsearch);
4374 if (__predict_false(error != 0)) {
4375 return (cache_fpl_aborted(fpl));
4376 }
4377 fpl->fsearch = fsearch;
4378 if ((*vpp)->v_type != VDIR) {
4379 if (!((cnp->cn_flags & EMPTYPATH) != 0 && cnp->cn_pnbuf[0] == '\0')) {
4380 cache_fpl_smr_exit(fpl);
4381 return (cache_fpl_handled_error(fpl, ENOTDIR));
4382 }
4383 }
4384 return (0);
4385 }
4386
4387 static int __noinline
cache_fplookup_negative_promote(struct cache_fpl * fpl,struct namecache * oncp,uint32_t hash)4388 cache_fplookup_negative_promote(struct cache_fpl *fpl, struct namecache *oncp,
4389 uint32_t hash)
4390 {
4391 struct componentname *cnp;
4392 struct vnode *dvp;
4393
4394 cnp = fpl->cnp;
4395 dvp = fpl->dvp;
4396
4397 cache_fpl_smr_exit(fpl);
4398 if (cache_neg_promote_cond(dvp, cnp, oncp, hash))
4399 return (cache_fpl_handled_error(fpl, ENOENT));
4400 else
4401 return (cache_fpl_aborted(fpl));
4402 }
4403
4404 /*
4405 * The target vnode is not supported, prepare for the slow path to take over.
4406 */
4407 static int __noinline
cache_fplookup_partial_setup(struct cache_fpl * fpl)4408 cache_fplookup_partial_setup(struct cache_fpl *fpl)
4409 {
4410 struct nameidata *ndp;
4411 struct componentname *cnp;
4412 enum vgetstate dvs;
4413 struct vnode *dvp;
4414 struct pwd *pwd;
4415 seqc_t dvp_seqc;
4416
4417 ndp = fpl->ndp;
4418 cnp = fpl->cnp;
4419 pwd = *(fpl->pwd);
4420 dvp = fpl->dvp;
4421 dvp_seqc = fpl->dvp_seqc;
4422
4423 if (!pwd_hold_smr(pwd)) {
4424 return (cache_fpl_aborted(fpl));
4425 }
4426
4427 /*
4428 * Note that seqc is checked before the vnode is locked, so by
4429 * the time regular lookup gets to it it may have moved.
4430 *
4431 * Ultimately this does not affect correctness, any lookup errors
4432 * are userspace racing with itself. It is guaranteed that any
4433 * path which ultimately gets found could also have been found
4434 * by regular lookup going all the way in absence of concurrent
4435 * modifications.
4436 */
4437 dvs = vget_prep_smr(dvp);
4438 cache_fpl_smr_exit(fpl);
4439 if (__predict_false(dvs == VGET_NONE)) {
4440 pwd_drop(pwd);
4441 return (cache_fpl_aborted(fpl));
4442 }
4443
4444 vget_finish_ref(dvp, dvs);
4445 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4446 vrele(dvp);
4447 pwd_drop(pwd);
4448 return (cache_fpl_aborted(fpl));
4449 }
4450
4451 cache_fpl_restore_partial(fpl);
4452 #ifdef INVARIANTS
4453 if (cnp->cn_nameptr != fpl->snd.cn_nameptr) {
4454 panic("%s: cn_nameptr mismatch (%p != %p) full [%s]\n", __func__,
4455 cnp->cn_nameptr, fpl->snd.cn_nameptr, cnp->cn_pnbuf);
4456 }
4457 #endif
4458
4459 ndp->ni_startdir = dvp;
4460 cnp->cn_flags |= MAKEENTRY;
4461 if (cache_fpl_islastcn(ndp))
4462 cnp->cn_flags |= ISLASTCN;
4463 if (cache_fpl_isdotdot(cnp))
4464 cnp->cn_flags |= ISDOTDOT;
4465
4466 /*
4467 * Skip potential extra slashes parsing did not take care of.
4468 * cache_fplookup_skip_slashes explains the mechanism.
4469 */
4470 if (__predict_false(*(cnp->cn_nameptr) == '/')) {
4471 do {
4472 cnp->cn_nameptr++;
4473 cache_fpl_pathlen_dec(fpl);
4474 } while (*(cnp->cn_nameptr) == '/');
4475 }
4476
4477 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
4478 #ifdef INVARIANTS
4479 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
4480 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
4481 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
4482 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
4483 }
4484 #endif
4485 return (0);
4486 }
4487
4488 static int
cache_fplookup_final_child(struct cache_fpl * fpl,enum vgetstate tvs)4489 cache_fplookup_final_child(struct cache_fpl *fpl, enum vgetstate tvs)
4490 {
4491 struct componentname *cnp;
4492 struct vnode *tvp;
4493 seqc_t tvp_seqc;
4494 int error, lkflags;
4495
4496 cnp = fpl->cnp;
4497 tvp = fpl->tvp;
4498 tvp_seqc = fpl->tvp_seqc;
4499
4500 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4501 lkflags = LK_SHARED;
4502 if ((cnp->cn_flags & LOCKSHARED) == 0)
4503 lkflags = LK_EXCLUSIVE;
4504 error = vget_finish(tvp, lkflags, tvs);
4505 if (__predict_false(error != 0)) {
4506 return (cache_fpl_aborted(fpl));
4507 }
4508 } else {
4509 vget_finish_ref(tvp, tvs);
4510 }
4511
4512 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
4513 if ((cnp->cn_flags & LOCKLEAF) != 0)
4514 vput(tvp);
4515 else
4516 vrele(tvp);
4517 return (cache_fpl_aborted(fpl));
4518 }
4519
4520 return (cache_fpl_handled(fpl));
4521 }
4522
4523 /*
4524 * They want to possibly modify the state of the namecache.
4525 */
4526 static int __noinline
cache_fplookup_final_modifying(struct cache_fpl * fpl)4527 cache_fplookup_final_modifying(struct cache_fpl *fpl)
4528 {
4529 struct nameidata *ndp;
4530 struct componentname *cnp;
4531 enum vgetstate dvs;
4532 struct vnode *dvp, *tvp;
4533 struct mount *mp;
4534 seqc_t dvp_seqc;
4535 int error;
4536 bool docache;
4537
4538 ndp = fpl->ndp;
4539 cnp = fpl->cnp;
4540 dvp = fpl->dvp;
4541 dvp_seqc = fpl->dvp_seqc;
4542
4543 MPASS(*(cnp->cn_nameptr) != '/');
4544 MPASS(cache_fpl_islastcn(ndp));
4545 if ((cnp->cn_flags & LOCKPARENT) == 0)
4546 MPASS((cnp->cn_flags & WANTPARENT) != 0);
4547 MPASS((cnp->cn_flags & TRAILINGSLASH) == 0);
4548 MPASS(cnp->cn_nameiop == CREATE || cnp->cn_nameiop == DELETE ||
4549 cnp->cn_nameiop == RENAME);
4550 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4551 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4552
4553 docache = (cnp->cn_flags & NOCACHE) ^ NOCACHE;
4554 if (cnp->cn_nameiop == DELETE || cnp->cn_nameiop == RENAME)
4555 docache = false;
4556
4557 /*
4558 * Regular lookup nulifies the slash, which we don't do here.
4559 * Don't take chances with filesystem routines seeing it for
4560 * the last entry.
4561 */
4562 if (cache_fpl_istrailingslash(fpl)) {
4563 return (cache_fpl_partial(fpl));
4564 }
4565
4566 mp = atomic_load_ptr(&dvp->v_mount);
4567 if (__predict_false(mp == NULL)) {
4568 return (cache_fpl_aborted(fpl));
4569 }
4570
4571 if (__predict_false(mp->mnt_flag & MNT_RDONLY)) {
4572 cache_fpl_smr_exit(fpl);
4573 /*
4574 * Original code keeps not checking for CREATE which
4575 * might be a bug. For now let the old lookup decide.
4576 */
4577 if (cnp->cn_nameiop == CREATE) {
4578 return (cache_fpl_aborted(fpl));
4579 }
4580 return (cache_fpl_handled_error(fpl, EROFS));
4581 }
4582
4583 if (fpl->tvp != NULL && (cnp->cn_flags & FAILIFEXISTS) != 0) {
4584 cache_fpl_smr_exit(fpl);
4585 return (cache_fpl_handled_error(fpl, EEXIST));
4586 }
4587
4588 /*
4589 * Secure access to dvp; check cache_fplookup_partial_setup for
4590 * reasoning.
4591 *
4592 * XXX At least UFS requires its lookup routine to be called for
4593 * the last path component, which leads to some level of complication
4594 * and inefficiency:
4595 * - the target routine always locks the target vnode, but our caller
4596 * may not need it locked
4597 * - some of the VOP machinery asserts that the parent is locked, which
4598 * once more may be not required
4599 *
4600 * TODO: add a flag for filesystems which don't need this.
4601 */
4602 dvs = vget_prep_smr(dvp);
4603 cache_fpl_smr_exit(fpl);
4604 if (__predict_false(dvs == VGET_NONE)) {
4605 return (cache_fpl_aborted(fpl));
4606 }
4607
4608 vget_finish_ref(dvp, dvs);
4609 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4610 vrele(dvp);
4611 return (cache_fpl_aborted(fpl));
4612 }
4613
4614 error = vn_lock(dvp, LK_EXCLUSIVE);
4615 if (__predict_false(error != 0)) {
4616 vrele(dvp);
4617 return (cache_fpl_aborted(fpl));
4618 }
4619
4620 tvp = NULL;
4621 cnp->cn_flags |= ISLASTCN;
4622 if (docache)
4623 cnp->cn_flags |= MAKEENTRY;
4624 if (cache_fpl_isdotdot(cnp))
4625 cnp->cn_flags |= ISDOTDOT;
4626 cnp->cn_lkflags = LK_EXCLUSIVE;
4627 error = VOP_LOOKUP(dvp, &tvp, cnp);
4628 switch (error) {
4629 case EJUSTRETURN:
4630 case 0:
4631 break;
4632 case ENOTDIR:
4633 case ENOENT:
4634 vput(dvp);
4635 return (cache_fpl_handled_error(fpl, error));
4636 default:
4637 vput(dvp);
4638 return (cache_fpl_aborted(fpl));
4639 }
4640
4641 fpl->tvp = tvp;
4642 fpl->savename = (cnp->cn_flags & SAVENAME) != 0;
4643
4644 if (tvp == NULL) {
4645 if ((cnp->cn_flags & SAVESTART) != 0) {
4646 ndp->ni_startdir = dvp;
4647 vrefact(ndp->ni_startdir);
4648 cnp->cn_flags |= SAVENAME;
4649 fpl->savename = true;
4650 }
4651 MPASS(error == EJUSTRETURN);
4652 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4653 VOP_UNLOCK(dvp);
4654 }
4655 return (cache_fpl_handled(fpl));
4656 }
4657
4658 /*
4659 * There are very hairy corner cases concerning various flag combinations
4660 * and locking state. In particular here we only hold one lock instead of
4661 * two.
4662 *
4663 * Skip the complexity as it is of no significance for normal workloads.
4664 */
4665 if (__predict_false(tvp == dvp)) {
4666 vput(dvp);
4667 vrele(tvp);
4668 return (cache_fpl_aborted(fpl));
4669 }
4670
4671 /*
4672 * If they want the symlink itself we are fine, but if they want to
4673 * follow it regular lookup has to be engaged.
4674 */
4675 if (tvp->v_type == VLNK) {
4676 if ((cnp->cn_flags & FOLLOW) != 0) {
4677 vput(dvp);
4678 vput(tvp);
4679 return (cache_fpl_aborted(fpl));
4680 }
4681 }
4682
4683 /*
4684 * Since we expect this to be the terminal vnode it should almost never
4685 * be a mount point.
4686 */
4687 if (__predict_false(cache_fplookup_is_mp(fpl))) {
4688 vput(dvp);
4689 vput(tvp);
4690 return (cache_fpl_aborted(fpl));
4691 }
4692
4693 if ((cnp->cn_flags & FAILIFEXISTS) != 0) {
4694 vput(dvp);
4695 vput(tvp);
4696 return (cache_fpl_handled_error(fpl, EEXIST));
4697 }
4698
4699 if ((cnp->cn_flags & LOCKLEAF) == 0) {
4700 VOP_UNLOCK(tvp);
4701 }
4702
4703 if ((cnp->cn_flags & LOCKPARENT) == 0) {
4704 VOP_UNLOCK(dvp);
4705 }
4706
4707 if ((cnp->cn_flags & SAVESTART) != 0) {
4708 ndp->ni_startdir = dvp;
4709 vrefact(ndp->ni_startdir);
4710 cnp->cn_flags |= SAVENAME;
4711 fpl->savename = true;
4712 }
4713
4714 return (cache_fpl_handled(fpl));
4715 }
4716
4717 static int __noinline
cache_fplookup_modifying(struct cache_fpl * fpl)4718 cache_fplookup_modifying(struct cache_fpl *fpl)
4719 {
4720 struct nameidata *ndp;
4721
4722 ndp = fpl->ndp;
4723
4724 if (!cache_fpl_islastcn(ndp)) {
4725 return (cache_fpl_partial(fpl));
4726 }
4727 return (cache_fplookup_final_modifying(fpl));
4728 }
4729
4730 static int __noinline
cache_fplookup_final_withparent(struct cache_fpl * fpl)4731 cache_fplookup_final_withparent(struct cache_fpl *fpl)
4732 {
4733 struct componentname *cnp;
4734 enum vgetstate dvs, tvs;
4735 struct vnode *dvp, *tvp;
4736 seqc_t dvp_seqc;
4737 int error;
4738
4739 cnp = fpl->cnp;
4740 dvp = fpl->dvp;
4741 dvp_seqc = fpl->dvp_seqc;
4742 tvp = fpl->tvp;
4743
4744 MPASS((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0);
4745
4746 /*
4747 * This is less efficient than it can be for simplicity.
4748 */
4749 dvs = vget_prep_smr(dvp);
4750 if (__predict_false(dvs == VGET_NONE)) {
4751 return (cache_fpl_aborted(fpl));
4752 }
4753 tvs = vget_prep_smr(tvp);
4754 if (__predict_false(tvs == VGET_NONE)) {
4755 cache_fpl_smr_exit(fpl);
4756 vget_abort(dvp, dvs);
4757 return (cache_fpl_aborted(fpl));
4758 }
4759
4760 cache_fpl_smr_exit(fpl);
4761
4762 if ((cnp->cn_flags & LOCKPARENT) != 0) {
4763 error = vget_finish(dvp, LK_EXCLUSIVE, dvs);
4764 if (__predict_false(error != 0)) {
4765 vget_abort(tvp, tvs);
4766 return (cache_fpl_aborted(fpl));
4767 }
4768 } else {
4769 vget_finish_ref(dvp, dvs);
4770 }
4771
4772 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4773 vget_abort(tvp, tvs);
4774 if ((cnp->cn_flags & LOCKPARENT) != 0)
4775 vput(dvp);
4776 else
4777 vrele(dvp);
4778 return (cache_fpl_aborted(fpl));
4779 }
4780
4781 error = cache_fplookup_final_child(fpl, tvs);
4782 if (__predict_false(error != 0)) {
4783 MPASS(fpl->status == CACHE_FPL_STATUS_ABORTED ||
4784 fpl->status == CACHE_FPL_STATUS_DESTROYED);
4785 if ((cnp->cn_flags & LOCKPARENT) != 0)
4786 vput(dvp);
4787 else
4788 vrele(dvp);
4789 return (error);
4790 }
4791
4792 MPASS(fpl->status == CACHE_FPL_STATUS_HANDLED);
4793 return (0);
4794 }
4795
4796 static int
cache_fplookup_final(struct cache_fpl * fpl)4797 cache_fplookup_final(struct cache_fpl *fpl)
4798 {
4799 struct componentname *cnp;
4800 enum vgetstate tvs;
4801 struct vnode *dvp, *tvp;
4802 seqc_t dvp_seqc;
4803
4804 cnp = fpl->cnp;
4805 dvp = fpl->dvp;
4806 dvp_seqc = fpl->dvp_seqc;
4807 tvp = fpl->tvp;
4808
4809 MPASS(*(cnp->cn_nameptr) != '/');
4810
4811 if (cnp->cn_nameiop != LOOKUP) {
4812 return (cache_fplookup_final_modifying(fpl));
4813 }
4814
4815 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0)
4816 return (cache_fplookup_final_withparent(fpl));
4817
4818 tvs = vget_prep_smr(tvp);
4819 if (__predict_false(tvs == VGET_NONE)) {
4820 return (cache_fpl_partial(fpl));
4821 }
4822
4823 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
4824 cache_fpl_smr_exit(fpl);
4825 vget_abort(tvp, tvs);
4826 return (cache_fpl_aborted(fpl));
4827 }
4828
4829 cache_fpl_smr_exit(fpl);
4830 return (cache_fplookup_final_child(fpl, tvs));
4831 }
4832
4833 /*
4834 * Comment from locked lookup:
4835 * Check for degenerate name (e.g. / or "") which is a way of talking about a
4836 * directory, e.g. like "/." or ".".
4837 */
4838 static int __noinline
cache_fplookup_degenerate(struct cache_fpl * fpl)4839 cache_fplookup_degenerate(struct cache_fpl *fpl)
4840 {
4841 struct componentname *cnp;
4842 struct vnode *dvp;
4843 enum vgetstate dvs;
4844 int error, lkflags;
4845 #ifdef INVARIANTS
4846 char *cp;
4847 #endif
4848
4849 fpl->tvp = fpl->dvp;
4850 fpl->tvp_seqc = fpl->dvp_seqc;
4851
4852 cnp = fpl->cnp;
4853 dvp = fpl->dvp;
4854
4855 #ifdef INVARIANTS
4856 for (cp = cnp->cn_pnbuf; *cp != '\0'; cp++) {
4857 KASSERT(*cp == '/',
4858 ("%s: encountered non-slash; string [%s]\n", __func__,
4859 cnp->cn_pnbuf));
4860 }
4861 #endif
4862
4863 if (__predict_false(cnp->cn_nameiop != LOOKUP)) {
4864 cache_fpl_smr_exit(fpl);
4865 return (cache_fpl_handled_error(fpl, EISDIR));
4866 }
4867
4868 MPASS((cnp->cn_flags & SAVESTART) == 0);
4869
4870 if ((cnp->cn_flags & (LOCKPARENT|WANTPARENT)) != 0) {
4871 return (cache_fplookup_final_withparent(fpl));
4872 }
4873
4874 dvs = vget_prep_smr(dvp);
4875 cache_fpl_smr_exit(fpl);
4876 if (__predict_false(dvs == VGET_NONE)) {
4877 return (cache_fpl_aborted(fpl));
4878 }
4879
4880 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4881 lkflags = LK_SHARED;
4882 if ((cnp->cn_flags & LOCKSHARED) == 0)
4883 lkflags = LK_EXCLUSIVE;
4884 error = vget_finish(dvp, lkflags, dvs);
4885 if (__predict_false(error != 0)) {
4886 return (cache_fpl_aborted(fpl));
4887 }
4888 } else {
4889 vget_finish_ref(dvp, dvs);
4890 }
4891 return (cache_fpl_handled(fpl));
4892 }
4893
4894 static int __noinline
cache_fplookup_emptypath(struct cache_fpl * fpl)4895 cache_fplookup_emptypath(struct cache_fpl *fpl)
4896 {
4897 struct nameidata *ndp;
4898 struct componentname *cnp;
4899 enum vgetstate tvs;
4900 struct vnode *tvp;
4901 int error, lkflags;
4902
4903 fpl->tvp = fpl->dvp;
4904 fpl->tvp_seqc = fpl->dvp_seqc;
4905
4906 ndp = fpl->ndp;
4907 cnp = fpl->cnp;
4908 tvp = fpl->tvp;
4909
4910 MPASS(*cnp->cn_pnbuf == '\0');
4911
4912 if (__predict_false((cnp->cn_flags & EMPTYPATH) == 0)) {
4913 cache_fpl_smr_exit(fpl);
4914 return (cache_fpl_handled_error(fpl, ENOENT));
4915 }
4916
4917 MPASS((cnp->cn_flags & (LOCKPARENT | WANTPARENT)) == 0);
4918
4919 tvs = vget_prep_smr(tvp);
4920 cache_fpl_smr_exit(fpl);
4921 if (__predict_false(tvs == VGET_NONE)) {
4922 return (cache_fpl_aborted(fpl));
4923 }
4924
4925 if ((cnp->cn_flags & LOCKLEAF) != 0) {
4926 lkflags = LK_SHARED;
4927 if ((cnp->cn_flags & LOCKSHARED) == 0)
4928 lkflags = LK_EXCLUSIVE;
4929 error = vget_finish(tvp, lkflags, tvs);
4930 if (__predict_false(error != 0)) {
4931 return (cache_fpl_aborted(fpl));
4932 }
4933 } else {
4934 vget_finish_ref(tvp, tvs);
4935 }
4936
4937 ndp->ni_resflags |= NIRES_EMPTYPATH;
4938 return (cache_fpl_handled(fpl));
4939 }
4940
4941 static int __noinline
cache_fplookup_noentry(struct cache_fpl * fpl)4942 cache_fplookup_noentry(struct cache_fpl *fpl)
4943 {
4944 struct nameidata *ndp;
4945 struct componentname *cnp;
4946 enum vgetstate dvs;
4947 struct vnode *dvp, *tvp;
4948 seqc_t dvp_seqc;
4949 int error;
4950
4951 ndp = fpl->ndp;
4952 cnp = fpl->cnp;
4953 dvp = fpl->dvp;
4954 dvp_seqc = fpl->dvp_seqc;
4955
4956 MPASS((cnp->cn_flags & MAKEENTRY) == 0);
4957 MPASS((cnp->cn_flags & ISDOTDOT) == 0);
4958 if (cnp->cn_nameiop == LOOKUP)
4959 MPASS((cnp->cn_flags & NOCACHE) == 0);
4960 MPASS(!cache_fpl_isdotdot(cnp));
4961
4962 /*
4963 * Hack: delayed name len checking.
4964 */
4965 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
4966 cache_fpl_smr_exit(fpl);
4967 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
4968 }
4969
4970 if (cnp->cn_nameptr[0] == '/') {
4971 return (cache_fplookup_skip_slashes(fpl));
4972 }
4973
4974 if (cnp->cn_pnbuf[0] == '\0') {
4975 return (cache_fplookup_emptypath(fpl));
4976 }
4977
4978 if (cnp->cn_nameptr[0] == '\0') {
4979 if (fpl->tvp == NULL) {
4980 return (cache_fplookup_degenerate(fpl));
4981 }
4982 return (cache_fplookup_trailingslash(fpl));
4983 }
4984
4985 if (cnp->cn_nameiop != LOOKUP) {
4986 fpl->tvp = NULL;
4987 return (cache_fplookup_modifying(fpl));
4988 }
4989
4990 MPASS((cnp->cn_flags & SAVESTART) == 0);
4991
4992 /*
4993 * Only try to fill in the component if it is the last one,
4994 * otherwise not only there may be several to handle but the
4995 * walk may be complicated.
4996 */
4997 if (!cache_fpl_islastcn(ndp)) {
4998 return (cache_fpl_partial(fpl));
4999 }
5000
5001 /*
5002 * Regular lookup nulifies the slash, which we don't do here.
5003 * Don't take chances with filesystem routines seeing it for
5004 * the last entry.
5005 */
5006 if (cache_fpl_istrailingslash(fpl)) {
5007 return (cache_fpl_partial(fpl));
5008 }
5009
5010 /*
5011 * Secure access to dvp; check cache_fplookup_partial_setup for
5012 * reasoning.
5013 */
5014 dvs = vget_prep_smr(dvp);
5015 cache_fpl_smr_exit(fpl);
5016 if (__predict_false(dvs == VGET_NONE)) {
5017 return (cache_fpl_aborted(fpl));
5018 }
5019
5020 vget_finish_ref(dvp, dvs);
5021 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
5022 vrele(dvp);
5023 return (cache_fpl_aborted(fpl));
5024 }
5025
5026 error = vn_lock(dvp, LK_SHARED);
5027 if (__predict_false(error != 0)) {
5028 vrele(dvp);
5029 return (cache_fpl_aborted(fpl));
5030 }
5031
5032 tvp = NULL;
5033 /*
5034 * TODO: provide variants which don't require locking either vnode.
5035 */
5036 cnp->cn_flags |= ISLASTCN | MAKEENTRY;
5037 cnp->cn_lkflags = LK_SHARED;
5038 if ((cnp->cn_flags & LOCKSHARED) == 0) {
5039 cnp->cn_lkflags = LK_EXCLUSIVE;
5040 }
5041 error = VOP_LOOKUP(dvp, &tvp, cnp);
5042 switch (error) {
5043 case EJUSTRETURN:
5044 case 0:
5045 break;
5046 case ENOTDIR:
5047 case ENOENT:
5048 vput(dvp);
5049 return (cache_fpl_handled_error(fpl, error));
5050 default:
5051 vput(dvp);
5052 return (cache_fpl_aborted(fpl));
5053 }
5054
5055 fpl->tvp = tvp;
5056 if (!fpl->savename) {
5057 MPASS((cnp->cn_flags & SAVENAME) == 0);
5058 }
5059
5060 if (tvp == NULL) {
5061 MPASS(error == EJUSTRETURN);
5062 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5063 vput(dvp);
5064 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5065 VOP_UNLOCK(dvp);
5066 }
5067 return (cache_fpl_handled(fpl));
5068 }
5069
5070 if (tvp->v_type == VLNK) {
5071 if ((cnp->cn_flags & FOLLOW) != 0) {
5072 vput(dvp);
5073 vput(tvp);
5074 return (cache_fpl_aborted(fpl));
5075 }
5076 }
5077
5078 if (__predict_false(cache_fplookup_is_mp(fpl))) {
5079 vput(dvp);
5080 vput(tvp);
5081 return (cache_fpl_aborted(fpl));
5082 }
5083
5084 if ((cnp->cn_flags & LOCKLEAF) == 0) {
5085 VOP_UNLOCK(tvp);
5086 }
5087
5088 if ((cnp->cn_flags & (WANTPARENT | LOCKPARENT)) == 0) {
5089 vput(dvp);
5090 } else if ((cnp->cn_flags & LOCKPARENT) == 0) {
5091 VOP_UNLOCK(dvp);
5092 }
5093 return (cache_fpl_handled(fpl));
5094 }
5095
5096 static int __noinline
cache_fplookup_dot(struct cache_fpl * fpl)5097 cache_fplookup_dot(struct cache_fpl *fpl)
5098 {
5099 int error;
5100
5101 MPASS(!seqc_in_modify(fpl->dvp_seqc));
5102
5103 if (__predict_false(fpl->dvp->v_type != VDIR)) {
5104 cache_fpl_smr_exit(fpl);
5105 return (cache_fpl_handled_error(fpl, ENOTDIR));
5106 }
5107
5108 /*
5109 * Just re-assign the value. seqc will be checked later for the first
5110 * non-dot path component in line and/or before deciding to return the
5111 * vnode.
5112 */
5113 fpl->tvp = fpl->dvp;
5114 fpl->tvp_seqc = fpl->dvp_seqc;
5115
5116 SDT_PROBE3(vfs, namecache, lookup, hit, fpl->dvp, ".", fpl->dvp);
5117
5118 error = 0;
5119 if (cache_fplookup_is_mp(fpl)) {
5120 error = cache_fplookup_cross_mount(fpl);
5121 }
5122 return (error);
5123 }
5124
5125 static int __noinline
cache_fplookup_dotdot(struct cache_fpl * fpl)5126 cache_fplookup_dotdot(struct cache_fpl *fpl)
5127 {
5128 struct nameidata *ndp;
5129 struct componentname *cnp;
5130 struct namecache *ncp;
5131 struct vnode *dvp;
5132 struct prison *pr;
5133 u_char nc_flag;
5134
5135 ndp = fpl->ndp;
5136 cnp = fpl->cnp;
5137 dvp = fpl->dvp;
5138
5139 MPASS(cache_fpl_isdotdot(cnp));
5140
5141 /*
5142 * XXX this is racy the same way regular lookup is
5143 */
5144 for (pr = cnp->cn_cred->cr_prison; pr != NULL;
5145 pr = pr->pr_parent)
5146 if (dvp == pr->pr_root)
5147 break;
5148
5149 if (dvp == ndp->ni_rootdir ||
5150 dvp == ndp->ni_topdir ||
5151 dvp == rootvnode ||
5152 pr != NULL) {
5153 fpl->tvp = dvp;
5154 fpl->tvp_seqc = vn_seqc_read_any(dvp);
5155 if (seqc_in_modify(fpl->tvp_seqc)) {
5156 return (cache_fpl_aborted(fpl));
5157 }
5158 return (0);
5159 }
5160
5161 if ((dvp->v_vflag & VV_ROOT) != 0) {
5162 /*
5163 * TODO
5164 * The opposite of climb mount is needed here.
5165 */
5166 return (cache_fpl_partial(fpl));
5167 }
5168
5169 if (__predict_false(dvp->v_type != VDIR)) {
5170 cache_fpl_smr_exit(fpl);
5171 return (cache_fpl_handled_error(fpl, ENOTDIR));
5172 }
5173
5174 ncp = atomic_load_consume_ptr(&dvp->v_cache_dd);
5175 if (ncp == NULL) {
5176 return (cache_fpl_aborted(fpl));
5177 }
5178
5179 nc_flag = atomic_load_char(&ncp->nc_flag);
5180 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5181 if ((nc_flag & NCF_NEGATIVE) != 0)
5182 return (cache_fpl_aborted(fpl));
5183 fpl->tvp = ncp->nc_vp;
5184 } else {
5185 fpl->tvp = ncp->nc_dvp;
5186 }
5187
5188 fpl->tvp_seqc = vn_seqc_read_any(fpl->tvp);
5189 if (seqc_in_modify(fpl->tvp_seqc)) {
5190 return (cache_fpl_partial(fpl));
5191 }
5192
5193 /*
5194 * Acquire fence provided by vn_seqc_read_any above.
5195 */
5196 if (__predict_false(atomic_load_ptr(&dvp->v_cache_dd) != ncp)) {
5197 return (cache_fpl_aborted(fpl));
5198 }
5199
5200 if (!cache_ncp_canuse(ncp)) {
5201 return (cache_fpl_aborted(fpl));
5202 }
5203
5204 return (0);
5205 }
5206
5207 static int __noinline
cache_fplookup_neg(struct cache_fpl * fpl,struct namecache * ncp,uint32_t hash)5208 cache_fplookup_neg(struct cache_fpl *fpl, struct namecache *ncp, uint32_t hash)
5209 {
5210 u_char nc_flag __diagused;
5211 bool neg_promote;
5212
5213 #ifdef INVARIANTS
5214 nc_flag = atomic_load_char(&ncp->nc_flag);
5215 MPASS((nc_flag & NCF_NEGATIVE) != 0);
5216 #endif
5217 /*
5218 * If they want to create an entry we need to replace this one.
5219 */
5220 if (__predict_false(fpl->cnp->cn_nameiop != LOOKUP)) {
5221 fpl->tvp = NULL;
5222 return (cache_fplookup_modifying(fpl));
5223 }
5224 neg_promote = cache_neg_hit_prep(ncp);
5225 if (!cache_fpl_neg_ncp_canuse(ncp)) {
5226 cache_neg_hit_abort(ncp);
5227 return (cache_fpl_partial(fpl));
5228 }
5229 if (neg_promote) {
5230 return (cache_fplookup_negative_promote(fpl, ncp, hash));
5231 }
5232 cache_neg_hit_finish(ncp);
5233 cache_fpl_smr_exit(fpl);
5234 return (cache_fpl_handled_error(fpl, ENOENT));
5235 }
5236
5237 /*
5238 * Resolve a symlink. Called by filesystem-specific routines.
5239 *
5240 * Code flow is:
5241 * ... -> cache_fplookup_symlink -> VOP_FPLOOKUP_SYMLINK -> cache_symlink_resolve
5242 */
5243 int
cache_symlink_resolve(struct cache_fpl * fpl,const char * string,size_t len)5244 cache_symlink_resolve(struct cache_fpl *fpl, const char *string, size_t len)
5245 {
5246 struct nameidata *ndp;
5247 struct componentname *cnp;
5248 size_t adjust;
5249
5250 ndp = fpl->ndp;
5251 cnp = fpl->cnp;
5252
5253 if (__predict_false(len == 0)) {
5254 return (ENOENT);
5255 }
5256
5257 if (__predict_false(len > MAXPATHLEN - 2)) {
5258 if (cache_fpl_istrailingslash(fpl)) {
5259 return (EAGAIN);
5260 }
5261 }
5262
5263 ndp->ni_pathlen = fpl->nulchar - cnp->cn_nameptr - cnp->cn_namelen + 1;
5264 #ifdef INVARIANTS
5265 if (ndp->ni_pathlen != fpl->debug.ni_pathlen) {
5266 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5267 __func__, ndp->ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5268 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5269 }
5270 #endif
5271
5272 if (__predict_false(len + ndp->ni_pathlen > MAXPATHLEN)) {
5273 return (ENAMETOOLONG);
5274 }
5275
5276 if (__predict_false(ndp->ni_loopcnt++ >= MAXSYMLINKS)) {
5277 return (ELOOP);
5278 }
5279
5280 adjust = len;
5281 if (ndp->ni_pathlen > 1) {
5282 bcopy(ndp->ni_next, cnp->cn_pnbuf + len, ndp->ni_pathlen);
5283 } else {
5284 if (cache_fpl_istrailingslash(fpl)) {
5285 adjust = len + 1;
5286 cnp->cn_pnbuf[len] = '/';
5287 cnp->cn_pnbuf[len + 1] = '\0';
5288 } else {
5289 cnp->cn_pnbuf[len] = '\0';
5290 }
5291 }
5292 bcopy(string, cnp->cn_pnbuf, len);
5293
5294 ndp->ni_pathlen += adjust;
5295 cache_fpl_pathlen_add(fpl, adjust);
5296 cnp->cn_nameptr = cnp->cn_pnbuf;
5297 fpl->nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
5298 fpl->tvp = NULL;
5299 return (0);
5300 }
5301
5302 static int __noinline
cache_fplookup_symlink(struct cache_fpl * fpl)5303 cache_fplookup_symlink(struct cache_fpl *fpl)
5304 {
5305 struct mount *mp;
5306 struct nameidata *ndp;
5307 struct componentname *cnp;
5308 struct vnode *dvp, *tvp;
5309 int error;
5310
5311 ndp = fpl->ndp;
5312 cnp = fpl->cnp;
5313 dvp = fpl->dvp;
5314 tvp = fpl->tvp;
5315
5316 if (cache_fpl_islastcn(ndp)) {
5317 if ((cnp->cn_flags & FOLLOW) == 0) {
5318 return (cache_fplookup_final(fpl));
5319 }
5320 }
5321
5322 mp = atomic_load_ptr(&dvp->v_mount);
5323 if (__predict_false(mp == NULL)) {
5324 return (cache_fpl_aborted(fpl));
5325 }
5326
5327 /*
5328 * Note this check races against setting the flag just like regular
5329 * lookup.
5330 */
5331 if (__predict_false((mp->mnt_flag & MNT_NOSYMFOLLOW) != 0)) {
5332 cache_fpl_smr_exit(fpl);
5333 return (cache_fpl_handled_error(fpl, EACCES));
5334 }
5335
5336 error = VOP_FPLOOKUP_SYMLINK(tvp, fpl);
5337 if (__predict_false(error != 0)) {
5338 switch (error) {
5339 case EAGAIN:
5340 return (cache_fpl_partial(fpl));
5341 case ENOENT:
5342 case ENAMETOOLONG:
5343 case ELOOP:
5344 cache_fpl_smr_exit(fpl);
5345 return (cache_fpl_handled_error(fpl, error));
5346 default:
5347 return (cache_fpl_aborted(fpl));
5348 }
5349 }
5350
5351 if (*(cnp->cn_nameptr) == '/') {
5352 fpl->dvp = cache_fpl_handle_root(fpl);
5353 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5354 if (seqc_in_modify(fpl->dvp_seqc)) {
5355 return (cache_fpl_aborted(fpl));
5356 }
5357 /*
5358 * The main loop assumes that ->dvp points to a vnode belonging
5359 * to a filesystem which can do lockless lookup, but the absolute
5360 * symlink can be wandering off to one which does not.
5361 */
5362 mp = atomic_load_ptr(&fpl->dvp->v_mount);
5363 if (__predict_false(mp == NULL)) {
5364 return (cache_fpl_aborted(fpl));
5365 }
5366 if (!cache_fplookup_mp_supported(mp)) {
5367 cache_fpl_checkpoint(fpl);
5368 return (cache_fpl_partial(fpl));
5369 }
5370 }
5371 return (0);
5372 }
5373
5374 static int
cache_fplookup_next(struct cache_fpl * fpl)5375 cache_fplookup_next(struct cache_fpl *fpl)
5376 {
5377 struct componentname *cnp;
5378 struct namecache *ncp;
5379 struct vnode *dvp, *tvp;
5380 u_char nc_flag;
5381 uint32_t hash;
5382 int error;
5383
5384 cnp = fpl->cnp;
5385 dvp = fpl->dvp;
5386 hash = fpl->hash;
5387
5388 if (__predict_false(cnp->cn_nameptr[0] == '.')) {
5389 if (cnp->cn_namelen == 1) {
5390 return (cache_fplookup_dot(fpl));
5391 }
5392 if (cnp->cn_namelen == 2 && cnp->cn_nameptr[1] == '.') {
5393 return (cache_fplookup_dotdot(fpl));
5394 }
5395 }
5396
5397 MPASS(!cache_fpl_isdotdot(cnp));
5398
5399 CK_SLIST_FOREACH(ncp, (NCHHASH(hash)), nc_hash) {
5400 if (ncp->nc_dvp == dvp && ncp->nc_nlen == cnp->cn_namelen &&
5401 !bcmp(ncp->nc_name, cnp->cn_nameptr, ncp->nc_nlen))
5402 break;
5403 }
5404
5405 if (__predict_false(ncp == NULL)) {
5406 return (cache_fplookup_noentry(fpl));
5407 }
5408
5409 tvp = atomic_load_ptr(&ncp->nc_vp);
5410 nc_flag = atomic_load_char(&ncp->nc_flag);
5411 if ((nc_flag & NCF_NEGATIVE) != 0) {
5412 return (cache_fplookup_neg(fpl, ncp, hash));
5413 }
5414
5415 if (!cache_ncp_canuse(ncp)) {
5416 return (cache_fpl_partial(fpl));
5417 }
5418
5419 fpl->tvp = tvp;
5420 fpl->tvp_seqc = vn_seqc_read_any(tvp);
5421 if (seqc_in_modify(fpl->tvp_seqc)) {
5422 return (cache_fpl_partial(fpl));
5423 }
5424
5425 counter_u64_add(numposhits, 1);
5426 SDT_PROBE3(vfs, namecache, lookup, hit, dvp, ncp->nc_name, tvp);
5427
5428 error = 0;
5429 if (cache_fplookup_is_mp(fpl)) {
5430 error = cache_fplookup_cross_mount(fpl);
5431 }
5432 return (error);
5433 }
5434
5435 static bool
cache_fplookup_mp_supported(struct mount * mp)5436 cache_fplookup_mp_supported(struct mount *mp)
5437 {
5438
5439 MPASS(mp != NULL);
5440 if ((mp->mnt_kern_flag & MNTK_FPLOOKUP) == 0)
5441 return (false);
5442 return (true);
5443 }
5444
5445 /*
5446 * Walk up the mount stack (if any).
5447 *
5448 * Correctness is provided in the following ways:
5449 * - all vnodes are protected from freeing with SMR
5450 * - struct mount objects are type stable making them always safe to access
5451 * - stability of the particular mount is provided by busying it
5452 * - relationship between the vnode which is mounted on and the mount is
5453 * verified with the vnode sequence counter after busying
5454 * - association between root vnode of the mount and the mount is protected
5455 * by busy
5456 *
5457 * From that point on we can read the sequence counter of the root vnode
5458 * and get the next mount on the stack (if any) using the same protection.
5459 *
5460 * By the end of successful walk we are guaranteed the reached state was
5461 * indeed present at least at some point which matches the regular lookup.
5462 */
5463 static int __noinline
cache_fplookup_climb_mount(struct cache_fpl * fpl)5464 cache_fplookup_climb_mount(struct cache_fpl *fpl)
5465 {
5466 struct mount *mp, *prev_mp;
5467 struct mount_pcpu *mpcpu, *prev_mpcpu;
5468 struct vnode *vp;
5469 seqc_t vp_seqc;
5470
5471 vp = fpl->tvp;
5472 vp_seqc = fpl->tvp_seqc;
5473
5474 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5475 mp = atomic_load_ptr(&vp->v_mountedhere);
5476 if (__predict_false(mp == NULL)) {
5477 return (0);
5478 }
5479
5480 prev_mp = NULL;
5481 for (;;) {
5482 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5483 if (prev_mp != NULL)
5484 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5485 return (cache_fpl_partial(fpl));
5486 }
5487 if (prev_mp != NULL)
5488 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5489 if (!vn_seqc_consistent(vp, vp_seqc)) {
5490 vfs_op_thread_exit_crit(mp, mpcpu);
5491 return (cache_fpl_partial(fpl));
5492 }
5493 if (!cache_fplookup_mp_supported(mp)) {
5494 vfs_op_thread_exit_crit(mp, mpcpu);
5495 return (cache_fpl_partial(fpl));
5496 }
5497 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5498 if (vp == NULL) {
5499 vfs_op_thread_exit_crit(mp, mpcpu);
5500 return (cache_fpl_partial(fpl));
5501 }
5502 vp_seqc = vn_seqc_read_any(vp);
5503 if (seqc_in_modify(vp_seqc)) {
5504 vfs_op_thread_exit_crit(mp, mpcpu);
5505 return (cache_fpl_partial(fpl));
5506 }
5507 prev_mp = mp;
5508 prev_mpcpu = mpcpu;
5509 mp = atomic_load_ptr(&vp->v_mountedhere);
5510 if (mp == NULL)
5511 break;
5512 }
5513
5514 vfs_op_thread_exit_crit(prev_mp, prev_mpcpu);
5515 fpl->tvp = vp;
5516 fpl->tvp_seqc = vp_seqc;
5517 return (0);
5518 }
5519
5520 static int __noinline
cache_fplookup_cross_mount(struct cache_fpl * fpl)5521 cache_fplookup_cross_mount(struct cache_fpl *fpl)
5522 {
5523 struct mount *mp;
5524 struct mount_pcpu *mpcpu;
5525 struct vnode *vp;
5526 seqc_t vp_seqc;
5527
5528 vp = fpl->tvp;
5529 vp_seqc = fpl->tvp_seqc;
5530
5531 VNPASS(vp->v_type == VDIR || vp->v_type == VREG || vp->v_type == VBAD, vp);
5532 mp = atomic_load_ptr(&vp->v_mountedhere);
5533 if (__predict_false(mp == NULL)) {
5534 return (0);
5535 }
5536
5537 if (!vfs_op_thread_enter_crit(mp, mpcpu)) {
5538 return (cache_fpl_partial(fpl));
5539 }
5540 if (!vn_seqc_consistent(vp, vp_seqc)) {
5541 vfs_op_thread_exit_crit(mp, mpcpu);
5542 return (cache_fpl_partial(fpl));
5543 }
5544 if (!cache_fplookup_mp_supported(mp)) {
5545 vfs_op_thread_exit_crit(mp, mpcpu);
5546 return (cache_fpl_partial(fpl));
5547 }
5548 vp = atomic_load_ptr(&mp->mnt_rootvnode);
5549 if (__predict_false(vp == NULL)) {
5550 vfs_op_thread_exit_crit(mp, mpcpu);
5551 return (cache_fpl_partial(fpl));
5552 }
5553 vp_seqc = vn_seqc_read_any(vp);
5554 vfs_op_thread_exit_crit(mp, mpcpu);
5555 if (seqc_in_modify(vp_seqc)) {
5556 return (cache_fpl_partial(fpl));
5557 }
5558 mp = atomic_load_ptr(&vp->v_mountedhere);
5559 if (__predict_false(mp != NULL)) {
5560 /*
5561 * There are possibly more mount points on top.
5562 * Normally this does not happen so for simplicity just start
5563 * over.
5564 */
5565 return (cache_fplookup_climb_mount(fpl));
5566 }
5567
5568 fpl->tvp = vp;
5569 fpl->tvp_seqc = vp_seqc;
5570 return (0);
5571 }
5572
5573 /*
5574 * Check if a vnode is mounted on.
5575 */
5576 static bool
cache_fplookup_is_mp(struct cache_fpl * fpl)5577 cache_fplookup_is_mp(struct cache_fpl *fpl)
5578 {
5579 struct vnode *vp;
5580
5581 vp = fpl->tvp;
5582 return ((vn_irflag_read(vp) & VIRF_MOUNTPOINT) != 0);
5583 }
5584
5585 /*
5586 * Parse the path.
5587 *
5588 * The code was originally copy-pasted from regular lookup and despite
5589 * clean ups leaves performance on the table. Any modifications here
5590 * must take into account that in case off fallback the resulting
5591 * nameidata state has to be compatible with the original.
5592 */
5593
5594 /*
5595 * Debug ni_pathlen tracking.
5596 */
5597 #ifdef INVARIANTS
5598 static void
cache_fpl_pathlen_add(struct cache_fpl * fpl,size_t n)5599 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5600 {
5601
5602 fpl->debug.ni_pathlen += n;
5603 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5604 ("%s: pathlen overflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5605 }
5606
5607 static void
cache_fpl_pathlen_sub(struct cache_fpl * fpl,size_t n)5608 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5609 {
5610
5611 fpl->debug.ni_pathlen -= n;
5612 KASSERT(fpl->debug.ni_pathlen <= PATH_MAX,
5613 ("%s: pathlen underflow to %zd\n", __func__, fpl->debug.ni_pathlen));
5614 }
5615
5616 static void
cache_fpl_pathlen_inc(struct cache_fpl * fpl)5617 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5618 {
5619
5620 cache_fpl_pathlen_add(fpl, 1);
5621 }
5622
5623 static void
cache_fpl_pathlen_dec(struct cache_fpl * fpl)5624 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5625 {
5626
5627 cache_fpl_pathlen_sub(fpl, 1);
5628 }
5629 #else
5630 static void
cache_fpl_pathlen_add(struct cache_fpl * fpl,size_t n)5631 cache_fpl_pathlen_add(struct cache_fpl *fpl, size_t n)
5632 {
5633 }
5634
5635 static void
cache_fpl_pathlen_sub(struct cache_fpl * fpl,size_t n)5636 cache_fpl_pathlen_sub(struct cache_fpl *fpl, size_t n)
5637 {
5638 }
5639
5640 static void
cache_fpl_pathlen_inc(struct cache_fpl * fpl)5641 cache_fpl_pathlen_inc(struct cache_fpl *fpl)
5642 {
5643 }
5644
5645 static void
cache_fpl_pathlen_dec(struct cache_fpl * fpl)5646 cache_fpl_pathlen_dec(struct cache_fpl *fpl)
5647 {
5648 }
5649 #endif
5650
5651 static void
cache_fplookup_parse(struct cache_fpl * fpl)5652 cache_fplookup_parse(struct cache_fpl *fpl)
5653 {
5654 struct nameidata *ndp;
5655 struct componentname *cnp;
5656 struct vnode *dvp;
5657 char *cp;
5658 uint32_t hash;
5659
5660 ndp = fpl->ndp;
5661 cnp = fpl->cnp;
5662 dvp = fpl->dvp;
5663
5664 /*
5665 * Find the end of this path component, it is either / or nul.
5666 *
5667 * Store / as a temporary sentinel so that we only have one character
5668 * to test for. Pathnames tend to be short so this should not be
5669 * resulting in cache misses.
5670 *
5671 * TODO: fix this to be word-sized.
5672 */
5673 MPASS(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] >= cnp->cn_pnbuf);
5674 KASSERT(&cnp->cn_nameptr[fpl->debug.ni_pathlen - 1] == fpl->nulchar,
5675 ("%s: mismatch between pathlen (%zu) and nulchar (%p != %p), string [%s]\n",
5676 __func__, fpl->debug.ni_pathlen, &cnp->cn_nameptr[fpl->debug.ni_pathlen - 1],
5677 fpl->nulchar, cnp->cn_pnbuf));
5678 KASSERT(*fpl->nulchar == '\0',
5679 ("%s: expected nul at %p; string [%s]\n", __func__, fpl->nulchar,
5680 cnp->cn_pnbuf));
5681 hash = cache_get_hash_iter_start(dvp);
5682 *fpl->nulchar = '/';
5683 for (cp = cnp->cn_nameptr; *cp != '/'; cp++) {
5684 KASSERT(*cp != '\0',
5685 ("%s: encountered unexpected nul; string [%s]\n", __func__,
5686 cnp->cn_nameptr));
5687 hash = cache_get_hash_iter(*cp, hash);
5688 continue;
5689 }
5690 *fpl->nulchar = '\0';
5691 fpl->hash = cache_get_hash_iter_finish(hash);
5692
5693 cnp->cn_namelen = cp - cnp->cn_nameptr;
5694 cache_fpl_pathlen_sub(fpl, cnp->cn_namelen);
5695
5696 #ifdef INVARIANTS
5697 /*
5698 * cache_get_hash only accepts lengths up to NAME_MAX. This is fine since
5699 * we are going to fail this lookup with ENAMETOOLONG (see below).
5700 */
5701 if (cnp->cn_namelen <= NAME_MAX) {
5702 if (fpl->hash != cache_get_hash(cnp->cn_nameptr, cnp->cn_namelen, dvp)) {
5703 panic("%s: mismatched hash for [%s] len %ld", __func__,
5704 cnp->cn_nameptr, cnp->cn_namelen);
5705 }
5706 }
5707 #endif
5708
5709 /*
5710 * Hack: we have to check if the found path component's length exceeds
5711 * NAME_MAX. However, the condition is very rarely true and check can
5712 * be elided in the common case -- if an entry was found in the cache,
5713 * then it could not have been too long to begin with.
5714 */
5715 ndp->ni_next = cp;
5716 }
5717
5718 static void
cache_fplookup_parse_advance(struct cache_fpl * fpl)5719 cache_fplookup_parse_advance(struct cache_fpl *fpl)
5720 {
5721 struct nameidata *ndp;
5722 struct componentname *cnp;
5723
5724 ndp = fpl->ndp;
5725 cnp = fpl->cnp;
5726
5727 cnp->cn_nameptr = ndp->ni_next;
5728 KASSERT(*(cnp->cn_nameptr) == '/',
5729 ("%s: should have seen slash at %p ; buf %p [%s]\n", __func__,
5730 cnp->cn_nameptr, cnp->cn_pnbuf, cnp->cn_pnbuf));
5731 cnp->cn_nameptr++;
5732 cache_fpl_pathlen_dec(fpl);
5733 }
5734
5735 /*
5736 * Skip spurious slashes in a pathname (e.g., "foo///bar") and retry.
5737 *
5738 * Lockless lookup tries to elide checking for spurious slashes and should they
5739 * be present is guaranteed to fail to find an entry. In this case the caller
5740 * must check if the name starts with a slash and call this routine. It is
5741 * going to fast forward across the spurious slashes and set the state up for
5742 * retry.
5743 */
5744 static int __noinline
cache_fplookup_skip_slashes(struct cache_fpl * fpl)5745 cache_fplookup_skip_slashes(struct cache_fpl *fpl)
5746 {
5747 struct nameidata *ndp;
5748 struct componentname *cnp;
5749
5750 ndp = fpl->ndp;
5751 cnp = fpl->cnp;
5752
5753 MPASS(*(cnp->cn_nameptr) == '/');
5754 do {
5755 cnp->cn_nameptr++;
5756 cache_fpl_pathlen_dec(fpl);
5757 } while (*(cnp->cn_nameptr) == '/');
5758
5759 /*
5760 * Go back to one slash so that cache_fplookup_parse_advance has
5761 * something to skip.
5762 */
5763 cnp->cn_nameptr--;
5764 cache_fpl_pathlen_inc(fpl);
5765
5766 /*
5767 * cache_fplookup_parse_advance starts from ndp->ni_next
5768 */
5769 ndp->ni_next = cnp->cn_nameptr;
5770
5771 /*
5772 * See cache_fplookup_dot.
5773 */
5774 fpl->tvp = fpl->dvp;
5775 fpl->tvp_seqc = fpl->dvp_seqc;
5776
5777 return (0);
5778 }
5779
5780 /*
5781 * Handle trailing slashes (e.g., "foo/").
5782 *
5783 * If a trailing slash is found the terminal vnode must be a directory.
5784 * Regular lookup shortens the path by nulifying the first trailing slash and
5785 * sets the TRAILINGSLASH flag to denote this took place. There are several
5786 * checks on it performed later.
5787 *
5788 * Similarly to spurious slashes, lockless lookup handles this in a speculative
5789 * manner relying on an invariant that a non-directory vnode will get a miss.
5790 * In this case cn_nameptr[0] == '\0' and cn_namelen == 0.
5791 *
5792 * Thus for a path like "foo/bar/" the code unwinds the state back to "bar/"
5793 * and denotes this is the last path component, which avoids looping back.
5794 *
5795 * Only plain lookups are supported for now to restrict corner cases to handle.
5796 */
5797 static int __noinline
cache_fplookup_trailingslash(struct cache_fpl * fpl)5798 cache_fplookup_trailingslash(struct cache_fpl *fpl)
5799 {
5800 #ifdef INVARIANTS
5801 size_t ni_pathlen;
5802 #endif
5803 struct nameidata *ndp;
5804 struct componentname *cnp;
5805 struct namecache *ncp;
5806 struct vnode *tvp;
5807 char *cn_nameptr_orig, *cn_nameptr_slash;
5808 seqc_t tvp_seqc;
5809 u_char nc_flag;
5810
5811 ndp = fpl->ndp;
5812 cnp = fpl->cnp;
5813 tvp = fpl->tvp;
5814 tvp_seqc = fpl->tvp_seqc;
5815
5816 MPASS(fpl->dvp == fpl->tvp);
5817 KASSERT(cache_fpl_istrailingslash(fpl),
5818 ("%s: expected trailing slash at %p; string [%s]\n", __func__, fpl->nulchar - 1,
5819 cnp->cn_pnbuf));
5820 KASSERT(cnp->cn_nameptr[0] == '\0',
5821 ("%s: expected nul char at %p; string [%s]\n", __func__, &cnp->cn_nameptr[0],
5822 cnp->cn_pnbuf));
5823 KASSERT(cnp->cn_namelen == 0,
5824 ("%s: namelen 0 but got %ld; string [%s]\n", __func__, cnp->cn_namelen,
5825 cnp->cn_pnbuf));
5826 MPASS(cnp->cn_nameptr > cnp->cn_pnbuf);
5827
5828 if (cnp->cn_nameiop != LOOKUP) {
5829 return (cache_fpl_aborted(fpl));
5830 }
5831
5832 if (__predict_false(tvp->v_type != VDIR)) {
5833 if (!vn_seqc_consistent(tvp, tvp_seqc)) {
5834 return (cache_fpl_aborted(fpl));
5835 }
5836 cache_fpl_smr_exit(fpl);
5837 return (cache_fpl_handled_error(fpl, ENOTDIR));
5838 }
5839
5840 /*
5841 * Denote the last component.
5842 */
5843 ndp->ni_next = &cnp->cn_nameptr[0];
5844 MPASS(cache_fpl_islastcn(ndp));
5845
5846 /*
5847 * Unwind trailing slashes.
5848 */
5849 cn_nameptr_orig = cnp->cn_nameptr;
5850 while (cnp->cn_nameptr >= cnp->cn_pnbuf) {
5851 cnp->cn_nameptr--;
5852 if (cnp->cn_nameptr[0] != '/') {
5853 break;
5854 }
5855 }
5856
5857 /*
5858 * Unwind to the beginning of the path component.
5859 *
5860 * Note the path may or may not have started with a slash.
5861 */
5862 cn_nameptr_slash = cnp->cn_nameptr;
5863 while (cnp->cn_nameptr > cnp->cn_pnbuf) {
5864 cnp->cn_nameptr--;
5865 if (cnp->cn_nameptr[0] == '/') {
5866 break;
5867 }
5868 }
5869 if (cnp->cn_nameptr[0] == '/') {
5870 cnp->cn_nameptr++;
5871 }
5872
5873 cnp->cn_namelen = cn_nameptr_slash - cnp->cn_nameptr + 1;
5874 cache_fpl_pathlen_add(fpl, cn_nameptr_orig - cnp->cn_nameptr);
5875 cache_fpl_checkpoint(fpl);
5876
5877 #ifdef INVARIANTS
5878 ni_pathlen = fpl->nulchar - cnp->cn_nameptr + 1;
5879 if (ni_pathlen != fpl->debug.ni_pathlen) {
5880 panic("%s: mismatch (%zu != %zu) nulchar %p nameptr %p [%s] ; full string [%s]\n",
5881 __func__, ni_pathlen, fpl->debug.ni_pathlen, fpl->nulchar,
5882 cnp->cn_nameptr, cnp->cn_nameptr, cnp->cn_pnbuf);
5883 }
5884 #endif
5885
5886 /*
5887 * If this was a "./" lookup the parent directory is already correct.
5888 */
5889 if (cnp->cn_nameptr[0] == '.' && cnp->cn_namelen == 1) {
5890 return (0);
5891 }
5892
5893 /*
5894 * Otherwise we need to look it up.
5895 */
5896 tvp = fpl->tvp;
5897 ncp = atomic_load_consume_ptr(&tvp->v_cache_dd);
5898 if (__predict_false(ncp == NULL)) {
5899 return (cache_fpl_aborted(fpl));
5900 }
5901 nc_flag = atomic_load_char(&ncp->nc_flag);
5902 if ((nc_flag & NCF_ISDOTDOT) != 0) {
5903 return (cache_fpl_aborted(fpl));
5904 }
5905 fpl->dvp = ncp->nc_dvp;
5906 fpl->dvp_seqc = vn_seqc_read_any(fpl->dvp);
5907 if (seqc_in_modify(fpl->dvp_seqc)) {
5908 return (cache_fpl_aborted(fpl));
5909 }
5910 return (0);
5911 }
5912
5913 /*
5914 * See the API contract for VOP_FPLOOKUP_VEXEC.
5915 */
5916 static int __noinline
cache_fplookup_failed_vexec(struct cache_fpl * fpl,int error)5917 cache_fplookup_failed_vexec(struct cache_fpl *fpl, int error)
5918 {
5919 struct componentname *cnp;
5920 struct vnode *dvp;
5921 seqc_t dvp_seqc;
5922
5923 cnp = fpl->cnp;
5924 dvp = fpl->dvp;
5925 dvp_seqc = fpl->dvp_seqc;
5926
5927 /*
5928 * Hack: delayed empty path checking.
5929 */
5930 if (cnp->cn_pnbuf[0] == '\0') {
5931 return (cache_fplookup_emptypath(fpl));
5932 }
5933
5934 /*
5935 * TODO: Due to ignoring trailing slashes lookup will perform a
5936 * permission check on the last dir when it should not be doing it. It
5937 * may fail, but said failure should be ignored. It is possible to fix
5938 * it up fully without resorting to regular lookup, but for now just
5939 * abort.
5940 */
5941 if (cache_fpl_istrailingslash(fpl)) {
5942 return (cache_fpl_aborted(fpl));
5943 }
5944
5945 /*
5946 * Hack: delayed degenerate path checking.
5947 */
5948 if (cnp->cn_nameptr[0] == '\0' && fpl->tvp == NULL) {
5949 return (cache_fplookup_degenerate(fpl));
5950 }
5951
5952 /*
5953 * Hack: delayed name len checking.
5954 */
5955 if (__predict_false(cnp->cn_namelen > NAME_MAX)) {
5956 cache_fpl_smr_exit(fpl);
5957 return (cache_fpl_handled_error(fpl, ENAMETOOLONG));
5958 }
5959
5960 /*
5961 * Hack: they may be looking up foo/bar, where foo is not a directory.
5962 * In such a case we need to return ENOTDIR, but we may happen to get
5963 * here with a different error.
5964 */
5965 if (dvp->v_type != VDIR) {
5966 error = ENOTDIR;
5967 }
5968
5969 /*
5970 * Hack: handle O_SEARCH.
5971 *
5972 * Open Group Base Specifications Issue 7, 2018 edition states:
5973 * <quote>
5974 * If the access mode of the open file description associated with the
5975 * file descriptor is not O_SEARCH, the function shall check whether
5976 * directory searches are permitted using the current permissions of
5977 * the directory underlying the file descriptor. If the access mode is
5978 * O_SEARCH, the function shall not perform the check.
5979 * </quote>
5980 *
5981 * Regular lookup tests for the NOEXECCHECK flag for every path
5982 * component to decide whether to do the permission check. However,
5983 * since most lookups never have the flag (and when they do it is only
5984 * present for the first path component), lockless lookup only acts on
5985 * it if there is a permission problem. Here the flag is represented
5986 * with a boolean so that we don't have to clear it on the way out.
5987 *
5988 * For simplicity this always aborts.
5989 * TODO: check if this is the first lookup and ignore the permission
5990 * problem. Note the flag has to survive fallback (if it happens to be
5991 * performed).
5992 */
5993 if (fpl->fsearch) {
5994 return (cache_fpl_aborted(fpl));
5995 }
5996
5997 switch (error) {
5998 case EAGAIN:
5999 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6000 error = cache_fpl_aborted(fpl);
6001 } else {
6002 cache_fpl_partial(fpl);
6003 }
6004 break;
6005 default:
6006 if (!vn_seqc_consistent(dvp, dvp_seqc)) {
6007 error = cache_fpl_aborted(fpl);
6008 } else {
6009 cache_fpl_smr_exit(fpl);
6010 cache_fpl_handled_error(fpl, error);
6011 }
6012 break;
6013 }
6014 return (error);
6015 }
6016
6017 static int
cache_fplookup_impl(struct vnode * dvp,struct cache_fpl * fpl)6018 cache_fplookup_impl(struct vnode *dvp, struct cache_fpl *fpl)
6019 {
6020 struct nameidata *ndp;
6021 struct componentname *cnp;
6022 struct mount *mp;
6023 int error;
6024
6025 ndp = fpl->ndp;
6026 cnp = fpl->cnp;
6027
6028 cache_fpl_checkpoint(fpl);
6029
6030 /*
6031 * The vnode at hand is almost always stable, skip checking for it.
6032 * Worst case this postpones the check towards the end of the iteration
6033 * of the main loop.
6034 */
6035 fpl->dvp = dvp;
6036 fpl->dvp_seqc = vn_seqc_read_notmodify(fpl->dvp);
6037
6038 mp = atomic_load_ptr(&dvp->v_mount);
6039 if (__predict_false(mp == NULL || !cache_fplookup_mp_supported(mp))) {
6040 return (cache_fpl_aborted(fpl));
6041 }
6042
6043 MPASS(fpl->tvp == NULL);
6044
6045 for (;;) {
6046 cache_fplookup_parse(fpl);
6047
6048 error = VOP_FPLOOKUP_VEXEC(fpl->dvp, cnp->cn_cred);
6049 if (__predict_false(error != 0)) {
6050 error = cache_fplookup_failed_vexec(fpl, error);
6051 break;
6052 }
6053
6054 error = cache_fplookup_next(fpl);
6055 if (__predict_false(cache_fpl_terminated(fpl))) {
6056 break;
6057 }
6058
6059 VNPASS(!seqc_in_modify(fpl->tvp_seqc), fpl->tvp);
6060
6061 if (fpl->tvp->v_type == VLNK) {
6062 error = cache_fplookup_symlink(fpl);
6063 if (cache_fpl_terminated(fpl)) {
6064 break;
6065 }
6066 } else {
6067 if (cache_fpl_islastcn(ndp)) {
6068 error = cache_fplookup_final(fpl);
6069 break;
6070 }
6071
6072 if (!vn_seqc_consistent(fpl->dvp, fpl->dvp_seqc)) {
6073 error = cache_fpl_aborted(fpl);
6074 break;
6075 }
6076
6077 fpl->dvp = fpl->tvp;
6078 fpl->dvp_seqc = fpl->tvp_seqc;
6079 cache_fplookup_parse_advance(fpl);
6080 }
6081
6082 cache_fpl_checkpoint(fpl);
6083 }
6084
6085 return (error);
6086 }
6087
6088 /*
6089 * Fast path lookup protected with SMR and sequence counters.
6090 *
6091 * Note: all VOP_FPLOOKUP_VEXEC routines have a comment referencing this one.
6092 *
6093 * Filesystems can opt in by setting the MNTK_FPLOOKUP flag and meeting criteria
6094 * outlined below.
6095 *
6096 * Traditional vnode lookup conceptually looks like this:
6097 *
6098 * vn_lock(current);
6099 * for (;;) {
6100 * next = find();
6101 * vn_lock(next);
6102 * vn_unlock(current);
6103 * current = next;
6104 * if (last)
6105 * break;
6106 * }
6107 * return (current);
6108 *
6109 * Each jump to the next vnode is safe memory-wise and atomic with respect to
6110 * any modifications thanks to holding respective locks.
6111 *
6112 * The same guarantee can be provided with a combination of safe memory
6113 * reclamation and sequence counters instead. If all operations which affect
6114 * the relationship between the current vnode and the one we are looking for
6115 * also modify the counter, we can verify whether all the conditions held as
6116 * we made the jump. This includes things like permissions, mount points etc.
6117 * Counter modification is provided by enclosing relevant places in
6118 * vn_seqc_write_begin()/end() calls.
6119 *
6120 * Thus this translates to:
6121 *
6122 * vfs_smr_enter();
6123 * dvp_seqc = seqc_read_any(dvp);
6124 * if (seqc_in_modify(dvp_seqc)) // someone is altering the vnode
6125 * abort();
6126 * for (;;) {
6127 * tvp = find();
6128 * tvp_seqc = seqc_read_any(tvp);
6129 * if (seqc_in_modify(tvp_seqc)) // someone is altering the target vnode
6130 * abort();
6131 * if (!seqc_consistent(dvp, dvp_seqc) // someone is altering the vnode
6132 * abort();
6133 * dvp = tvp; // we know nothing of importance has changed
6134 * dvp_seqc = tvp_seqc; // store the counter for the tvp iteration
6135 * if (last)
6136 * break;
6137 * }
6138 * vget(); // secure the vnode
6139 * if (!seqc_consistent(tvp, tvp_seqc) // final check
6140 * abort();
6141 * // at this point we know nothing has changed for any parent<->child pair
6142 * // as they were crossed during the lookup, meaning we matched the guarantee
6143 * // of the locked variant
6144 * return (tvp);
6145 *
6146 * The API contract for VOP_FPLOOKUP_VEXEC routines is as follows:
6147 * - they are called while within vfs_smr protection which they must never exit
6148 * - EAGAIN can be returned to denote checking could not be performed, it is
6149 * always valid to return it
6150 * - if the sequence counter has not changed the result must be valid
6151 * - if the sequence counter has changed both false positives and false negatives
6152 * are permitted (since the result will be rejected later)
6153 * - for simple cases of unix permission checks vaccess_vexec_smr can be used
6154 *
6155 * Caveats to watch out for:
6156 * - vnodes are passed unlocked and unreferenced with nothing stopping
6157 * VOP_RECLAIM, in turn meaning that ->v_data can become NULL. It is advised
6158 * to use atomic_load_ptr to fetch it.
6159 * - the aforementioned object can also get freed, meaning absent other means it
6160 * should be protected with vfs_smr
6161 * - either safely checking permissions as they are modified or guaranteeing
6162 * their stability is left to the routine
6163 */
6164 int
cache_fplookup(struct nameidata * ndp,enum cache_fpl_status * status,struct pwd ** pwdp)6165 cache_fplookup(struct nameidata *ndp, enum cache_fpl_status *status,
6166 struct pwd **pwdp)
6167 {
6168 struct cache_fpl fpl;
6169 struct pwd *pwd;
6170 struct vnode *dvp;
6171 struct componentname *cnp;
6172 int error;
6173
6174 fpl.status = CACHE_FPL_STATUS_UNSET;
6175 fpl.in_smr = false;
6176 fpl.ndp = ndp;
6177 fpl.cnp = cnp = &ndp->ni_cnd;
6178 MPASS(ndp->ni_lcf == 0);
6179 MPASS(curthread == cnp->cn_thread);
6180 KASSERT ((cnp->cn_flags & CACHE_FPL_INTERNAL_CN_FLAGS) == 0,
6181 ("%s: internal flags found in cn_flags %" PRIx64, __func__,
6182 cnp->cn_flags));
6183 if ((cnp->cn_flags & SAVESTART) != 0) {
6184 MPASS(cnp->cn_nameiop != LOOKUP);
6185 }
6186 MPASS(cnp->cn_nameptr == cnp->cn_pnbuf);
6187
6188 if (__predict_false(!cache_can_fplookup(&fpl))) {
6189 *status = fpl.status;
6190 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6191 return (EOPNOTSUPP);
6192 }
6193
6194 cache_fpl_checkpoint_outer(&fpl);
6195
6196 cache_fpl_smr_enter_initial(&fpl);
6197 #ifdef INVARIANTS
6198 fpl.debug.ni_pathlen = ndp->ni_pathlen;
6199 #endif
6200 fpl.nulchar = &cnp->cn_nameptr[ndp->ni_pathlen - 1];
6201 fpl.fsearch = false;
6202 fpl.savename = (cnp->cn_flags & SAVENAME) != 0;
6203 fpl.tvp = NULL; /* for degenerate path handling */
6204 fpl.pwd = pwdp;
6205 pwd = pwd_get_smr();
6206 *(fpl.pwd) = pwd;
6207 ndp->ni_rootdir = pwd->pwd_rdir;
6208 ndp->ni_topdir = pwd->pwd_jdir;
6209
6210 if (cnp->cn_pnbuf[0] == '/') {
6211 dvp = cache_fpl_handle_root(&fpl);
6212 MPASS(ndp->ni_resflags == 0);
6213 ndp->ni_resflags = NIRES_ABS;
6214 } else {
6215 if (ndp->ni_dirfd == AT_FDCWD) {
6216 dvp = pwd->pwd_cdir;
6217 } else {
6218 error = cache_fplookup_dirfd(&fpl, &dvp);
6219 if (__predict_false(error != 0)) {
6220 goto out;
6221 }
6222 }
6223 }
6224
6225 SDT_PROBE4(vfs, namei, lookup, entry, dvp, cnp->cn_pnbuf, cnp->cn_flags, true);
6226 error = cache_fplookup_impl(dvp, &fpl);
6227 out:
6228 cache_fpl_smr_assert_not_entered(&fpl);
6229 cache_fpl_assert_status(&fpl);
6230 *status = fpl.status;
6231 if (SDT_PROBES_ENABLED()) {
6232 SDT_PROBE3(vfs, fplookup, lookup, done, ndp, fpl.line, fpl.status);
6233 if (fpl.status == CACHE_FPL_STATUS_HANDLED)
6234 SDT_PROBE4(vfs, namei, lookup, return, error, ndp->ni_vp, true,
6235 ndp);
6236 }
6237
6238 if (__predict_true(fpl.status == CACHE_FPL_STATUS_HANDLED)) {
6239 MPASS(error != CACHE_FPL_FAILED);
6240 if (error != 0) {
6241 MPASS(fpl.dvp == NULL);
6242 MPASS(fpl.tvp == NULL);
6243 MPASS(fpl.savename == false);
6244 }
6245 ndp->ni_dvp = fpl.dvp;
6246 ndp->ni_vp = fpl.tvp;
6247 if (fpl.savename) {
6248 cnp->cn_flags |= HASBUF;
6249 } else {
6250 cache_fpl_cleanup_cnp(cnp);
6251 }
6252 }
6253 return (error);
6254 }
6255