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