vfs_cache.c revision 1.132 1 /* $NetBSD: vfs_cache.c,v 1.132 2020/03/23 18:56:14 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2008, 2019, 2020 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
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 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32 /*
33 * Copyright (c) 1989, 1993
34 * The Regents of the University of California. All rights reserved.
35 *
36 * Redistribution and use in source and binary forms, with or without
37 * modification, are permitted provided that the following conditions
38 * are met:
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 * @(#)vfs_cache.c 8.3 (Berkeley) 8/22/94
61 */
62
63 /*
64 * Name caching:
65 *
66 * Names found by directory scans are retained in a cache for future
67 * reference. It is managed LRU, so frequently used names will hang
68 * around. The cache is indexed by hash value obtained from the name.
69 *
70 * The name cache is the brainchild of Robert Elz and was introduced in
71 * 4.3BSD. See "Using gprof to Tune the 4.2BSD Kernel", Marshall Kirk
72 * McKusick, May 21 1984.
73 *
74 * Data structures:
75 *
76 * Most Unix namecaches very sensibly use a global hash table to index
77 * names. The global hash table works well, but can cause concurrency
78 * headaches for the kernel hacker. In the NetBSD 10.0 implementation
79 * we are not sensible, and use a per-directory data structure to index
80 * names, but the cache otherwise functions the same.
81 *
82 * The index is a red-black tree. There are no special concurrency
83 * requirements placed on it, because it's per-directory and protected
84 * by the namecache's per-directory locks. It should therefore not be
85 * difficult to experiment with other types of index.
86 *
87 * Each cached name is stored in a struct namecache, along with a
88 * pointer to the associated vnode (nc_vp). Names longer than a
89 * maximum length of NCHNAMLEN are allocated with kmem_alloc(); they
90 * occur infrequently, and names shorter than this are stored directly
91 * in struct namecache. If it is a "negative" entry, (i.e. for a name
92 * that is known NOT to exist) the vnode pointer will be NULL.
93 *
94 * For a directory with 3 cached names for 3 distinct vnodes, the
95 * various vnodes and namecache structs would be connected like this
96 * (the root is at the bottom of the diagram):
97 *
98 * ...
99 * ^
100 * |- vi_nc_tree
101 * |
102 * +----o----+ +---------+ +---------+
103 * | VDIR | | VCHR | | VREG |
104 * | vnode o-----+ | vnode o-----+ | vnode o------+
105 * +---------+ | +---------+ | +---------+ |
106 * ^ | ^ | ^ |
107 * |- nc_vp |- vi_nc_list |- nc_vp |- vi_nc_list |- nc_vp |
108 * | | | | | |
109 * +----o----+ | +----o----+ | +----o----+ |
110 * +---onamecache|<----+ +---onamecache|<----+ +---onamecache|<-----+
111 * | +---------+ | +---------+ | +---------+
112 * | ^ | ^ | ^
113 * | | | | | |
114 * | | +----------------------+ | |
115 * |-nc_dvp | +-------------------------------------------------+
116 * | |/- vi_nc_tree | |
117 * | | |- nc_dvp |- nc_dvp
118 * | +----o----+ | |
119 * +-->| VDIR |<----------+ |
120 * | vnode |<------------------------------------+
121 * +---------+
122 *
123 * START HERE
124 *
125 * Replacement:
126 *
127 * As the cache becomes full, old and unused entries are purged as new
128 * entries are added. The synchronization overhead in maintaining a
129 * strict ordering would be prohibitive, so the VM system's "clock" or
130 * "second chance" page replacement algorithm is aped here. New
131 * entries go to the tail of the active list. After they age out and
132 * reach the head of the list, they are moved to the tail of the
133 * inactive list. Any use of the deactivated cache entry reactivates
134 * it, saving it from impending doom; if not reactivated, the entry
135 * eventually reaches the head of the inactive list and is purged.
136 *
137 * Concurrency:
138 *
139 * From a performance perspective, cache_lookup(nameiop == LOOKUP) is
140 * what really matters; insertion of new entries with cache_enter() is
141 * comparatively infrequent, and overshadowed by the cost of expensive
142 * file system metadata operations (which may involve disk I/O). We
143 * therefore want to make everything simplest in the lookup path.
144 *
145 * struct namecache is mostly stable except for list and tree related
146 * entries, changes to which don't affect the cached name or vnode.
147 * For changes to name+vnode, entries are purged in preference to
148 * modifying them.
149 *
150 * Read access to namecache entries is made via tree, list, or LRU
151 * list. A lock corresponding to the direction of access should be
152 * held. See definition of "struct namecache" in src/sys/namei.src,
153 * and the definition of "struct vnode" for the particulars.
154 *
155 * Per-CPU statistics, and LRU list totals are read unlocked, since
156 * an approximate value is OK. We maintain 32-bit sized per-CPU
157 * counters and 64-bit global counters under the theory that 32-bit
158 * sized counters are less likely to be hosed by nonatomic increment
159 * (on 32-bit platforms).
160 *
161 * The lock order is:
162 *
163 * 1) vi->vi_nc_lock (tree or parent -> child direction,
164 * used during forward lookup)
165 *
166 * 2) vi->vi_nc_listlock (list or child -> parent direction,
167 * used during reverse lookup)
168 *
169 * 3) cache_lru_lock (LRU list direction, used during reclaim)
170 *
171 * 4) vp->v_interlock (what the cache entry points to)
172 */
173
174 #include <sys/cdefs.h>
175 __KERNEL_RCSID(0, "$NetBSD: vfs_cache.c,v 1.132 2020/03/23 18:56:14 ad Exp $");
176
177 #define __NAMECACHE_PRIVATE
178 #ifdef _KERNEL_OPT
179 #include "opt_ddb.h"
180 #include "opt_dtrace.h"
181 #endif
182
183 #include <sys/types.h>
184 #include <sys/atomic.h>
185 #include <sys/callout.h>
186 #include <sys/cpu.h>
187 #include <sys/errno.h>
188 #include <sys/evcnt.h>
189 #include <sys/hash.h>
190 #include <sys/kernel.h>
191 #include <sys/mount.h>
192 #include <sys/mutex.h>
193 #include <sys/namei.h>
194 #include <sys/param.h>
195 #include <sys/pool.h>
196 #include <sys/sdt.h>
197 #include <sys/sysctl.h>
198 #include <sys/systm.h>
199 #include <sys/time.h>
200 #include <sys/vnode_impl.h>
201
202 #include <miscfs/genfs/genfs.h>
203
204 static void cache_activate(struct namecache *);
205 static void cache_update_stats(void *);
206 static int cache_compare_nodes(void *, const void *, const void *);
207 static void cache_deactivate(void);
208 static void cache_reclaim(void);
209 static int cache_stat_sysctl(SYSCTLFN_ARGS);
210
211 /*
212 * Global pool cache.
213 */
214 static pool_cache_t cache_pool __read_mostly;
215
216 /*
217 * LRU replacement.
218 */
219 enum cache_lru_id {
220 LRU_ACTIVE,
221 LRU_INACTIVE,
222 LRU_COUNT
223 };
224
225 static struct {
226 TAILQ_HEAD(, namecache) list[LRU_COUNT];
227 u_int count[LRU_COUNT];
228 } cache_lru __cacheline_aligned;
229
230 static kmutex_t cache_lru_lock __cacheline_aligned;
231
232 /*
233 * Cache effectiveness statistics. nchstats holds system-wide total.
234 */
235 struct nchstats nchstats;
236 struct nchstats_percpu _NAMEI_CACHE_STATS(uint32_t);
237 struct nchcpu {
238 struct nchstats_percpu cur;
239 struct nchstats_percpu last;
240 };
241 static callout_t cache_stat_callout;
242 static kmutex_t cache_stat_lock __cacheline_aligned;
243
244 #define COUNT(f) do { \
245 lwp_t *l = curlwp; \
246 KPREEMPT_DISABLE(l); \
247 ((struct nchstats_percpu *)curcpu()->ci_data.cpu_nch)->f++; \
248 KPREEMPT_ENABLE(l); \
249 } while (/* CONSTCOND */ 0);
250
251 #define UPDATE(nchcpu, f) do { \
252 uint32_t cur = atomic_load_relaxed(&nchcpu->cur.f); \
253 nchstats.f += cur - nchcpu->last.f; \
254 nchcpu->last.f = cur; \
255 } while (/* CONSTCOND */ 0)
256
257 /*
258 * Tunables. cache_maxlen replaces the historical doingcache:
259 * set it zero to disable caching for debugging purposes.
260 */
261 int cache_lru_maxdeact __read_mostly = 2; /* max # to deactivate */
262 int cache_lru_maxscan __read_mostly = 64; /* max # to scan/reclaim */
263 int cache_maxlen __read_mostly = USHRT_MAX; /* max name length to cache */
264 int cache_stat_interval __read_mostly = 300; /* in seconds */
265
266 /*
267 * sysctl stuff.
268 */
269 static struct sysctllog *cache_sysctllog;
270
271 /*
272 * Red-black tree stuff.
273 */
274 static const rb_tree_ops_t cache_rbtree_ops = {
275 .rbto_compare_nodes = cache_compare_nodes,
276 .rbto_compare_key = cache_compare_nodes,
277 .rbto_node_offset = offsetof(struct namecache, nc_tree),
278 .rbto_context = NULL
279 };
280
281 /*
282 * dtrace probes.
283 */
284 SDT_PROVIDER_DEFINE(vfs);
285
286 SDT_PROBE_DEFINE1(vfs, namecache, invalidate, done, "struct vnode *");
287 SDT_PROBE_DEFINE1(vfs, namecache, purge, parents, "struct vnode *");
288 SDT_PROBE_DEFINE1(vfs, namecache, purge, children, "struct vnode *");
289 SDT_PROBE_DEFINE2(vfs, namecache, purge, name, "char *", "size_t");
290 SDT_PROBE_DEFINE1(vfs, namecache, purge, vfs, "struct mount *");
291 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *",
292 "char *", "size_t");
293 SDT_PROBE_DEFINE3(vfs, namecache, lookup, miss, "struct vnode *",
294 "char *", "size_t");
295 SDT_PROBE_DEFINE3(vfs, namecache, lookup, toolong, "struct vnode *",
296 "char *", "size_t");
297 SDT_PROBE_DEFINE2(vfs, namecache, revlookup, success, "struct vnode *",
298 "struct vnode *");
299 SDT_PROBE_DEFINE2(vfs, namecache, revlookup, fail, "struct vnode *",
300 "int");
301 SDT_PROBE_DEFINE2(vfs, namecache, prune, done, "int", "int");
302 SDT_PROBE_DEFINE3(vfs, namecache, enter, toolong, "struct vnode *",
303 "char *", "size_t");
304 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *",
305 "char *", "size_t");
306
307 /*
308 * rbtree: compare two nodes.
309 */
310 static int
311 cache_compare_nodes(void *context, const void *n1, const void *n2)
312 {
313 const struct namecache *nc1 = n1;
314 const struct namecache *nc2 = n2;
315
316 if (nc1->nc_key < nc2->nc_key) {
317 return -1;
318 }
319 if (nc1->nc_key > nc2->nc_key) {
320 return 1;
321 }
322 KASSERT(nc1->nc_nlen == nc2->nc_nlen);
323 return memcmp(nc1->nc_name, nc2->nc_name, nc1->nc_nlen);
324 }
325
326 /*
327 * Compute a key value for the given name. The name length is encoded in
328 * the key value to try and improve uniqueness, and so that length doesn't
329 * need to be compared separately for string comparisons.
330 */
331 static inline uint64_t
332 cache_key(const char *name, size_t nlen)
333 {
334 uint64_t key;
335
336 KASSERT(nlen <= USHRT_MAX);
337
338 key = hash32_buf(name, nlen, HASH32_STR_INIT);
339 return (key << 32) | nlen;
340 }
341
342 /*
343 * Remove an entry from the cache. vi_nc_lock must be held, and if dir2node
344 * is true, then we're locking in the conventional direction and the list
345 * lock will be acquired when removing the entry from the vnode list.
346 */
347 static void
348 cache_remove(struct namecache *ncp, const bool dir2node)
349 {
350 struct vnode *vp, *dvp = ncp->nc_dvp;
351 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
352
353 KASSERT(rw_write_held(&dvi->vi_nc_lock));
354 KASSERT(cache_key(ncp->nc_name, ncp->nc_nlen) == ncp->nc_key);
355 KASSERT(rb_tree_find_node(&dvi->vi_nc_tree, ncp) == ncp);
356
357 SDT_PROBE(vfs, namecache, invalidate, done, ncp,
358 0, 0, 0, 0);
359
360 /* First remove from the directory's rbtree. */
361 rb_tree_remove_node(&dvi->vi_nc_tree, ncp);
362
363 /* Then remove from the LRU lists. */
364 mutex_enter(&cache_lru_lock);
365 TAILQ_REMOVE(&cache_lru.list[ncp->nc_lrulist], ncp, nc_lru);
366 cache_lru.count[ncp->nc_lrulist]--;
367 mutex_exit(&cache_lru_lock);
368
369 /* Then remove from the node's list. */
370 if ((vp = ncp->nc_vp) != NULL) {
371 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
372 if (__predict_true(dir2node)) {
373 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
374 TAILQ_REMOVE(&vi->vi_nc_list, ncp, nc_list);
375 rw_exit(&vi->vi_nc_listlock);
376 } else {
377 TAILQ_REMOVE(&vi->vi_nc_list, ncp, nc_list);
378 }
379 }
380
381 /* Finally, free it. */
382 if (ncp->nc_nlen > NCHNAMLEN) {
383 size_t sz = offsetof(struct namecache, nc_name[ncp->nc_nlen]);
384 kmem_free(ncp, sz);
385 } else {
386 pool_cache_put(cache_pool, ncp);
387 }
388 }
389
390 /*
391 * Find a single cache entry and return it. vi_nc_lock must be held.
392 */
393 static struct namecache * __noinline
394 cache_lookup_entry(struct vnode *dvp, const char *name, size_t namelen,
395 uint64_t key)
396 {
397 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
398 struct rb_node *node = dvi->vi_nc_tree.rbt_root;
399 struct namecache *ncp;
400 int lrulist, diff;
401
402 KASSERT(rw_lock_held(&dvi->vi_nc_lock));
403
404 /*
405 * Search the RB tree for the key. This is an inlined lookup
406 * tailored for exactly what's needed here (64-bit key and so on)
407 * that is quite a bit faster than using rb_tree_find_node().
408 *
409 * In the fast path memcmp() needs to be called at least once to
410 * confirm that the correct name has been found. If there has been
411 * a hash value collision (very rare) the search will continue on.
412 */
413 for (;;) {
414 if (__predict_false(RB_SENTINEL_P(node))) {
415 return NULL;
416 }
417 KASSERT((void *)&ncp->nc_tree == (void *)ncp);
418 ncp = (struct namecache *)node;
419 KASSERT(ncp->nc_dvp == dvp);
420 if (__predict_false(ncp->nc_key == key)) {
421 KASSERT(ncp->nc_nlen == namelen);
422 diff = memcmp(ncp->nc_name, name, namelen);
423 if (__predict_true(diff == 0)) {
424 break;
425 }
426 node = node->rb_nodes[diff < 0];
427 } else {
428 node = node->rb_nodes[ncp->nc_key < key];
429 }
430 }
431
432 /*
433 * If the entry is on the wrong LRU list, requeue it. This is an
434 * unlocked check, but it will rarely be wrong and even then there
435 * will be no harm caused.
436 */
437 lrulist = atomic_load_relaxed(&ncp->nc_lrulist);
438 if (__predict_false(lrulist != LRU_ACTIVE)) {
439 cache_activate(ncp);
440 }
441 return ncp;
442 }
443
444 /*
445 * Look for a the name in the cache. We don't do this
446 * if the segment name is long, simply so the cache can avoid
447 * holding long names (which would either waste space, or
448 * add greatly to the complexity).
449 *
450 * Lookup is called with DVP pointing to the directory to search,
451 * and CNP providing the name of the entry being sought: cn_nameptr
452 * is the name, cn_namelen is its length, and cn_flags is the flags
453 * word from the namei operation.
454 *
455 * DVP must be locked.
456 *
457 * There are three possible non-error return states:
458 * 1. Nothing was found in the cache. Nothing is known about
459 * the requested name.
460 * 2. A negative entry was found in the cache, meaning that the
461 * requested name definitely does not exist.
462 * 3. A positive entry was found in the cache, meaning that the
463 * requested name does exist and that we are providing the
464 * vnode.
465 * In these cases the results are:
466 * 1. 0 returned; VN is set to NULL.
467 * 2. 1 returned; VN is set to NULL.
468 * 3. 1 returned; VN is set to the vnode found.
469 *
470 * The additional result argument ISWHT is set to zero, unless a
471 * negative entry is found that was entered as a whiteout, in which
472 * case ISWHT is set to one.
473 *
474 * The ISWHT_RET argument pointer may be null. In this case an
475 * assertion is made that the whiteout flag is not set. File systems
476 * that do not support whiteouts can/should do this.
477 *
478 * Filesystems that do support whiteouts should add ISWHITEOUT to
479 * cnp->cn_flags if ISWHT comes back nonzero.
480 *
481 * When a vnode is returned, it is locked, as per the vnode lookup
482 * locking protocol.
483 *
484 * There is no way for this function to fail, in the sense of
485 * generating an error that requires aborting the namei operation.
486 *
487 * (Prior to October 2012, this function returned an integer status,
488 * and a vnode, and mucked with the flags word in CNP for whiteouts.
489 * The integer status was -1 for "nothing found", ENOENT for "a
490 * negative entry found", 0 for "a positive entry found", and possibly
491 * other errors, and the value of VN might or might not have been set
492 * depending on what error occurred.)
493 */
494 bool
495 cache_lookup(struct vnode *dvp, const char *name, size_t namelen,
496 uint32_t nameiop, uint32_t cnflags,
497 int *iswht_ret, struct vnode **vn_ret)
498 {
499 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
500 struct namecache *ncp;
501 struct vnode *vp;
502 uint64_t key;
503 int error;
504 bool hit;
505 krw_t op;
506
507 /* Establish default result values */
508 if (iswht_ret != NULL) {
509 *iswht_ret = 0;
510 }
511 *vn_ret = NULL;
512
513 if (__predict_false(namelen > cache_maxlen)) {
514 SDT_PROBE(vfs, namecache, lookup, toolong, dvp,
515 name, namelen, 0, 0);
516 COUNT(ncs_long);
517 return false;
518 }
519
520 /* Compute the key up front - don't need the lock. */
521 key = cache_key(name, namelen);
522
523 /* Could the entry be purged below? */
524 if ((cnflags & ISLASTCN) != 0 &&
525 ((cnflags & MAKEENTRY) == 0 || nameiop == CREATE)) {
526 op = RW_WRITER;
527 } else {
528 op = RW_READER;
529 }
530
531 /* Now look for the name. */
532 rw_enter(&dvi->vi_nc_lock, op);
533 ncp = cache_lookup_entry(dvp, name, namelen, key);
534 if (__predict_false(ncp == NULL)) {
535 rw_exit(&dvi->vi_nc_lock);
536 COUNT(ncs_miss);
537 SDT_PROBE(vfs, namecache, lookup, miss, dvp,
538 name, namelen, 0, 0);
539 return false;
540 }
541 if (__predict_false((cnflags & MAKEENTRY) == 0)) {
542 /*
543 * Last component and we are renaming or deleting,
544 * the cache entry is invalid, or otherwise don't
545 * want cache entry to exist.
546 */
547 KASSERT((cnflags & ISLASTCN) != 0);
548 cache_remove(ncp, true);
549 rw_exit(&dvi->vi_nc_lock);
550 COUNT(ncs_badhits);
551 return false;
552 }
553 if (ncp->nc_vp == NULL) {
554 if (nameiop == CREATE && (cnflags & ISLASTCN) != 0) {
555 /*
556 * Last component and we are preparing to create
557 * the named object, so flush the negative cache
558 * entry.
559 */
560 COUNT(ncs_badhits);
561 cache_remove(ncp, true);
562 hit = false;
563 } else {
564 COUNT(ncs_neghits);
565 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name,
566 namelen, 0, 0);
567 /* found neg entry; vn is already null from above */
568 hit = true;
569 }
570 if (iswht_ret != NULL) {
571 /*
572 * Restore the ISWHITEOUT flag saved earlier.
573 */
574 *iswht_ret = ncp->nc_whiteout;
575 } else {
576 KASSERT(!ncp->nc_whiteout);
577 }
578 rw_exit(&dvi->vi_nc_lock);
579 return hit;
580 }
581 vp = ncp->nc_vp;
582 mutex_enter(vp->v_interlock);
583 rw_exit(&dvi->vi_nc_lock);
584
585 /*
586 * Unlocked except for the vnode interlock. Call vcache_tryvget().
587 */
588 error = vcache_tryvget(vp);
589 if (error) {
590 KASSERT(error == EBUSY);
591 /*
592 * This vnode is being cleaned out.
593 * XXX badhits?
594 */
595 COUNT(ncs_falsehits);
596 return false;
597 }
598
599 COUNT(ncs_goodhits);
600 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
601 /* found it */
602 *vn_ret = vp;
603 return true;
604 }
605
606 /*
607 * Version of the above without the nameiop argument, for NFS.
608 */
609 bool
610 cache_lookup_raw(struct vnode *dvp, const char *name, size_t namelen,
611 uint32_t cnflags,
612 int *iswht_ret, struct vnode **vn_ret)
613 {
614
615 return cache_lookup(dvp, name, namelen, LOOKUP, cnflags | MAKEENTRY,
616 iswht_ret, vn_ret);
617 }
618
619 /*
620 * Used by namei() to walk down a path, component by component by looking up
621 * names in the cache. The node locks are chained along the way: a parent's
622 * lock is not dropped until the child's is acquired.
623 */
624 bool
625 cache_lookup_linked(struct vnode *dvp, const char *name, size_t namelen,
626 struct vnode **vn_ret, krwlock_t **plock,
627 kauth_cred_t cred)
628 {
629 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
630 struct namecache *ncp;
631 uint64_t key;
632 int error;
633
634 /* Establish default results. */
635 *vn_ret = NULL;
636
637 /* If disabled, or file system doesn't support this, bail out. */
638 if (__predict_false((dvp->v_mount->mnt_iflag & IMNT_NCLOOKUP) == 0)) {
639 return false;
640 }
641
642 if (__predict_false(namelen > cache_maxlen)) {
643 COUNT(ncs_long);
644 return false;
645 }
646
647 /* Compute the key up front - don't need the lock. */
648 key = cache_key(name, namelen);
649
650 /*
651 * Acquire the directory lock. Once we have that, we can drop the
652 * previous one (if any).
653 *
654 * The two lock holds mean that the directory can't go away while
655 * here: the directory must be purged with cache_purge() before
656 * being freed, and both parent & child's vi_nc_lock must be taken
657 * before that point is passed.
658 *
659 * However if there's no previous lock, like at the root of the
660 * chain, then "dvp" must be referenced to prevent dvp going away
661 * before we get its lock.
662 *
663 * Note that the two locks can be the same if looking up a dot, for
664 * example: /usr/bin/.
665 */
666 if (*plock != &dvi->vi_nc_lock) {
667 rw_enter(&dvi->vi_nc_lock, RW_READER);
668 if (*plock != NULL) {
669 rw_exit(*plock);
670 }
671 *plock = &dvi->vi_nc_lock;
672 } else if (*plock == NULL) {
673 KASSERT(dvp->v_usecount > 0);
674 }
675
676 /*
677 * First up check if the user is allowed to look up files in this
678 * directory.
679 */
680 KASSERT(dvi->vi_nc_mode != VNOVAL && dvi->vi_nc_uid != VNOVAL &&
681 dvi->vi_nc_gid != VNOVAL);
682 error = kauth_authorize_vnode(cred, KAUTH_ACCESS_ACTION(VEXEC,
683 dvp->v_type, dvi->vi_nc_mode & ALLPERMS), dvp, NULL,
684 genfs_can_access(dvp->v_type, dvi->vi_nc_mode & ALLPERMS,
685 dvi->vi_nc_uid, dvi->vi_nc_gid, VEXEC, cred));
686 if (error != 0) {
687 COUNT(ncs_denied);
688 return false;
689 }
690
691 /*
692 * Now look for a matching cache entry.
693 */
694 ncp = cache_lookup_entry(dvp, name, namelen, key);
695 if (__predict_false(ncp == NULL)) {
696 COUNT(ncs_miss);
697 SDT_PROBE(vfs, namecache, lookup, miss, dvp,
698 name, namelen, 0, 0);
699 return false;
700 }
701 if (ncp->nc_vp == NULL) {
702 /* found negative entry; vn is already null from above */
703 COUNT(ncs_neghits);
704 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
705 return true;
706 }
707
708 COUNT(ncs_goodhits); /* XXX can be "badhits" */
709 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
710
711 /*
712 * Return with the directory lock still held. It will either be
713 * returned to us with another call to cache_lookup_linked() when
714 * looking up the next component, or the caller will release it
715 * manually when finished.
716 */
717 *vn_ret = ncp->nc_vp;
718 return true;
719 }
720
721 /*
722 * Scan cache looking for name of directory entry pointing at vp.
723 * Will not search for "." or "..".
724 *
725 * If the lookup succeeds the vnode is referenced and stored in dvpp.
726 *
727 * If bufp is non-NULL, also place the name in the buffer which starts
728 * at bufp, immediately before *bpp, and move bpp backwards to point
729 * at the start of it. (Yes, this is a little baroque, but it's done
730 * this way to cater to the whims of getcwd).
731 *
732 * Returns 0 on success, -1 on cache miss, positive errno on failure.
733 */
734 int
735 cache_revlookup(struct vnode *vp, struct vnode **dvpp, char **bpp, char *bufp,
736 bool checkaccess, int perms)
737 {
738 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
739 struct namecache *ncp;
740 struct vnode *dvp;
741 int error, nlen, lrulist;
742 char *bp;
743
744 KASSERT(vp != NULL);
745
746 if (cache_maxlen == 0)
747 goto out;
748
749 rw_enter(&vi->vi_nc_listlock, RW_READER);
750 if (checkaccess) {
751 /*
752 * Check if the user is allowed to see. NOTE: this is
753 * checking for access on the "wrong" directory. getcwd()
754 * wants to see that there is access on every component
755 * along the way, not that there is access to any individual
756 * component. Don't use this to check you can look in vp.
757 *
758 * I don't like it, I didn't come up with it, don't blame me!
759 */
760 KASSERT(vi->vi_nc_mode != VNOVAL && vi->vi_nc_uid != VNOVAL &&
761 vi->vi_nc_gid != VNOVAL);
762 error = kauth_authorize_vnode(curlwp->l_cred,
763 KAUTH_ACCESS_ACTION(VEXEC, vp->v_type, vi->vi_nc_mode &
764 ALLPERMS), vp, NULL, genfs_can_access(vp->v_type,
765 vi->vi_nc_mode & ALLPERMS, vi->vi_nc_uid, vi->vi_nc_gid,
766 perms, curlwp->l_cred));
767 if (error != 0) {
768 rw_exit(&vi->vi_nc_listlock);
769 COUNT(ncs_denied);
770 return EACCES;
771 }
772 }
773 TAILQ_FOREACH(ncp, &vi->vi_nc_list, nc_list) {
774 KASSERT(ncp->nc_vp == vp);
775 KASSERT(ncp->nc_dvp != NULL);
776 nlen = ncp->nc_nlen;
777
778 /*
779 * The queue is partially sorted. Once we hit dots, nothing
780 * else remains but dots and dotdots, so bail out.
781 */
782 if (ncp->nc_name[0] == '.') {
783 if (nlen == 1 ||
784 (nlen == 2 && ncp->nc_name[1] == '.')) {
785 break;
786 }
787 }
788
789 /* Record a hit on the entry. This is an unlocked read. */
790 lrulist = atomic_load_relaxed(&ncp->nc_lrulist);
791 if (lrulist != LRU_ACTIVE) {
792 cache_activate(ncp);
793 }
794
795 if (bufp) {
796 bp = *bpp;
797 bp -= nlen;
798 if (bp <= bufp) {
799 *dvpp = NULL;
800 rw_exit(&vi->vi_nc_listlock);
801 SDT_PROBE(vfs, namecache, revlookup,
802 fail, vp, ERANGE, 0, 0, 0);
803 return (ERANGE);
804 }
805 memcpy(bp, ncp->nc_name, nlen);
806 *bpp = bp;
807 }
808
809 dvp = ncp->nc_dvp;
810 mutex_enter(dvp->v_interlock);
811 rw_exit(&vi->vi_nc_listlock);
812 error = vcache_tryvget(dvp);
813 if (error) {
814 KASSERT(error == EBUSY);
815 if (bufp)
816 (*bpp) += nlen;
817 *dvpp = NULL;
818 SDT_PROBE(vfs, namecache, revlookup, fail, vp,
819 error, 0, 0, 0);
820 return -1;
821 }
822 *dvpp = dvp;
823 SDT_PROBE(vfs, namecache, revlookup, success, vp, dvp,
824 0, 0, 0);
825 COUNT(ncs_revhits);
826 return (0);
827 }
828 rw_exit(&vi->vi_nc_listlock);
829 COUNT(ncs_revmiss);
830 out:
831 *dvpp = NULL;
832 return (-1);
833 }
834
835 /*
836 * Add an entry to the cache.
837 */
838 void
839 cache_enter(struct vnode *dvp, struct vnode *vp,
840 const char *name, size_t namelen, uint32_t cnflags)
841 {
842 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
843 struct namecache *ncp, *oncp;
844 int total;
845
846 /* First, check whether we can/should add a cache entry. */
847 if ((cnflags & MAKEENTRY) == 0 ||
848 __predict_false(namelen > cache_maxlen)) {
849 SDT_PROBE(vfs, namecache, enter, toolong, vp, name, namelen,
850 0, 0);
851 return;
852 }
853
854 SDT_PROBE(vfs, namecache, enter, done, vp, name, namelen, 0, 0);
855
856 /*
857 * Reclaim some entries if over budget. This is an unlocked check,
858 * but it doesn't matter. Just need to catch up with things
859 * eventually: it doesn't matter if we go over temporarily.
860 */
861 total = atomic_load_relaxed(&cache_lru.count[LRU_ACTIVE]);
862 total += atomic_load_relaxed(&cache_lru.count[LRU_INACTIVE]);
863 if (__predict_false(total > desiredvnodes)) {
864 cache_reclaim();
865 }
866
867 /* Now allocate a fresh entry. */
868 if (__predict_true(namelen <= NCHNAMLEN)) {
869 ncp = pool_cache_get(cache_pool, PR_WAITOK);
870 } else {
871 size_t sz = offsetof(struct namecache, nc_name[namelen]);
872 ncp = kmem_alloc(sz, KM_SLEEP);
873 }
874
875 /*
876 * Fill in cache info. For negative hits, save the ISWHITEOUT flag
877 * so we can restore it later when the cache entry is used again.
878 */
879 ncp->nc_vp = vp;
880 ncp->nc_dvp = dvp;
881 ncp->nc_key = cache_key(name, namelen);
882 ncp->nc_nlen = namelen;
883 ncp->nc_whiteout = ((cnflags & ISWHITEOUT) != 0);
884 memcpy(ncp->nc_name, name, namelen);
885
886 /*
887 * Insert to the directory. Concurrent lookups may race for a cache
888 * entry. If there's a entry there already, purge it.
889 */
890 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
891 oncp = rb_tree_insert_node(&dvi->vi_nc_tree, ncp);
892 if (oncp != ncp) {
893 KASSERT(oncp->nc_key == ncp->nc_key);
894 KASSERT(oncp->nc_nlen == ncp->nc_nlen);
895 KASSERT(memcmp(oncp->nc_name, name, namelen) == 0);
896 cache_remove(oncp, true);
897 oncp = rb_tree_insert_node(&dvi->vi_nc_tree, ncp);
898 KASSERT(oncp == ncp);
899 }
900
901 /*
902 * With the directory lock still held, insert to the tail of the
903 * ACTIVE LRU list (new) and with the LRU lock held take the to
904 * opportunity to incrementally balance the lists.
905 */
906 mutex_enter(&cache_lru_lock);
907 ncp->nc_lrulist = LRU_ACTIVE;
908 cache_lru.count[LRU_ACTIVE]++;
909 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
910 cache_deactivate();
911 mutex_exit(&cache_lru_lock);
912
913 /*
914 * Finally, insert to the vnode, and unlock. Partially sort the
915 * per-vnode list: dots go to back.
916 */
917 if (vp != NULL) {
918 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
919 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
920 if ((namelen == 1 && name[0] == '.') ||
921 (namelen == 2 && name[0] == '.' && name[1] == '.')) {
922 TAILQ_INSERT_TAIL(&vi->vi_nc_list, ncp, nc_list);
923 } else {
924 TAILQ_INSERT_HEAD(&vi->vi_nc_list, ncp, nc_list);
925 }
926 rw_exit(&vi->vi_nc_listlock);
927 }
928 rw_exit(&dvi->vi_nc_lock);
929 }
930
931 /*
932 * Set identity info in cache for a vnode. We only care about directories
933 * so ignore other updates.
934 */
935 void
936 cache_enter_id(struct vnode *vp, mode_t mode, uid_t uid, gid_t gid)
937 {
938 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
939
940 if (vp->v_type == VDIR) {
941 /* Grab both locks, for forward & reverse lookup. */
942 rw_enter(&vi->vi_nc_lock, RW_WRITER);
943 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
944 vi->vi_nc_mode = mode;
945 vi->vi_nc_uid = uid;
946 vi->vi_nc_gid = gid;
947 rw_exit(&vi->vi_nc_listlock);
948 rw_exit(&vi->vi_nc_lock);
949 }
950 }
951
952 /*
953 * Return true if we have identity for the given vnode, and use as an
954 * opportunity to confirm that everything squares up.
955 *
956 * Because of shared code, some file systems could provide partial
957 * information, missing some updates, so always check the mount flag
958 * instead of looking for !VNOVAL.
959 */
960 bool
961 cache_have_id(struct vnode *vp)
962 {
963
964 if (vp->v_type == VDIR &&
965 (vp->v_mount->mnt_iflag & IMNT_NCLOOKUP) != 0) {
966 KASSERT(VNODE_TO_VIMPL(vp)->vi_nc_mode != VNOVAL);
967 KASSERT(VNODE_TO_VIMPL(vp)->vi_nc_uid != VNOVAL);
968 KASSERT(VNODE_TO_VIMPL(vp)->vi_nc_gid != VNOVAL);
969 return true;
970 } else {
971 return false;
972 }
973 }
974
975 /*
976 * Name cache initialization, from vfs_init() when the system is booting.
977 */
978 void
979 nchinit(void)
980 {
981
982 cache_pool = pool_cache_init(sizeof(struct namecache),
983 coherency_unit, 0, 0, "nchentry", NULL, IPL_NONE, NULL,
984 NULL, NULL);
985 KASSERT(cache_pool != NULL);
986
987 mutex_init(&cache_lru_lock, MUTEX_DEFAULT, IPL_NONE);
988 TAILQ_INIT(&cache_lru.list[LRU_ACTIVE]);
989 TAILQ_INIT(&cache_lru.list[LRU_INACTIVE]);
990
991 mutex_init(&cache_stat_lock, MUTEX_DEFAULT, IPL_NONE);
992 callout_init(&cache_stat_callout, CALLOUT_MPSAFE);
993 callout_setfunc(&cache_stat_callout, cache_update_stats, NULL);
994 callout_schedule(&cache_stat_callout, cache_stat_interval * hz);
995
996 KASSERT(cache_sysctllog == NULL);
997 sysctl_createv(&cache_sysctllog, 0, NULL, NULL,
998 CTLFLAG_PERMANENT,
999 CTLTYPE_STRUCT, "namecache_stats",
1000 SYSCTL_DESCR("namecache statistics"),
1001 cache_stat_sysctl, 0, NULL, 0,
1002 CTL_VFS, CTL_CREATE, CTL_EOL);
1003 }
1004
1005 /*
1006 * Called once for each CPU in the system as attached.
1007 */
1008 void
1009 cache_cpu_init(struct cpu_info *ci)
1010 {
1011 void *p;
1012 size_t sz;
1013
1014 sz = roundup2(sizeof(struct nchstats_percpu), coherency_unit) +
1015 coherency_unit;
1016 p = kmem_zalloc(sz, KM_SLEEP);
1017 ci->ci_data.cpu_nch = (void *)roundup2((uintptr_t)p, coherency_unit);
1018 }
1019
1020 /*
1021 * A vnode is being allocated: set up cache structures.
1022 */
1023 void
1024 cache_vnode_init(struct vnode *vp)
1025 {
1026 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
1027
1028 rw_init(&vi->vi_nc_lock);
1029 rw_init(&vi->vi_nc_listlock);
1030 rb_tree_init(&vi->vi_nc_tree, &cache_rbtree_ops);
1031 TAILQ_INIT(&vi->vi_nc_list);
1032 vi->vi_nc_mode = VNOVAL;
1033 vi->vi_nc_uid = VNOVAL;
1034 vi->vi_nc_gid = VNOVAL;
1035 }
1036
1037 /*
1038 * A vnode is being freed: finish cache structures.
1039 */
1040 void
1041 cache_vnode_fini(struct vnode *vp)
1042 {
1043 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
1044
1045 KASSERT(RB_TREE_MIN(&vi->vi_nc_tree) == NULL);
1046 KASSERT(TAILQ_EMPTY(&vi->vi_nc_list));
1047 rw_destroy(&vi->vi_nc_lock);
1048 rw_destroy(&vi->vi_nc_listlock);
1049 }
1050
1051 /*
1052 * Helper for cache_purge1(): purge cache entries for the given vnode from
1053 * all directories that the vnode is cached in.
1054 */
1055 static void
1056 cache_purge_parents(struct vnode *vp)
1057 {
1058 vnode_impl_t *dvi, *vi = VNODE_TO_VIMPL(vp);
1059 struct vnode *dvp, *blocked;
1060 struct namecache *ncp;
1061
1062 SDT_PROBE(vfs, namecache, purge, parents, vp, 0, 0, 0, 0);
1063
1064 blocked = NULL;
1065
1066 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
1067 while ((ncp = TAILQ_FIRST(&vi->vi_nc_list)) != NULL) {
1068 /*
1069 * Locking in the wrong direction. Try for a hold on the
1070 * directory node's lock, and if we get it then all good,
1071 * nuke the entry and move on to the next.
1072 */
1073 dvp = ncp->nc_dvp;
1074 dvi = VNODE_TO_VIMPL(dvp);
1075 if (rw_tryenter(&dvi->vi_nc_lock, RW_WRITER)) {
1076 cache_remove(ncp, false);
1077 rw_exit(&dvi->vi_nc_lock);
1078 blocked = NULL;
1079 continue;
1080 }
1081
1082 /*
1083 * We can't wait on the directory node's lock with our list
1084 * lock held or the system could deadlock.
1085 *
1086 * Take a hold on the directory vnode to prevent it from
1087 * being freed (taking the vnode & lock with it). Then
1088 * wait for the lock to become available with no other locks
1089 * held, and retry.
1090 *
1091 * If this happens twice in a row, give the other side a
1092 * breather; we can do nothing until it lets go.
1093 */
1094 vhold(dvp);
1095 rw_exit(&vi->vi_nc_listlock);
1096 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
1097 /* Do nothing. */
1098 rw_exit(&dvi->vi_nc_lock);
1099 holdrele(dvp);
1100 if (blocked == dvp) {
1101 kpause("ncpurge", false, 1, NULL);
1102 }
1103 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
1104 blocked = dvp;
1105 }
1106 rw_exit(&vi->vi_nc_listlock);
1107 }
1108
1109 /*
1110 * Helper for cache_purge1(): purge all cache entries hanging off the given
1111 * directory vnode.
1112 */
1113 static void
1114 cache_purge_children(struct vnode *dvp)
1115 {
1116 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
1117 struct namecache *ncp;
1118
1119 SDT_PROBE(vfs, namecache, purge, children, dvp, 0, 0, 0, 0);
1120
1121 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
1122 for (;;) {
1123 ncp = rb_tree_iterate(&dvi->vi_nc_tree, NULL, RB_DIR_RIGHT);
1124 if (ncp == NULL) {
1125 break;
1126 }
1127 cache_remove(ncp, true);
1128 }
1129 rw_exit(&dvi->vi_nc_lock);
1130 }
1131
1132 /*
1133 * Helper for cache_purge1(): purge cache entry from the given vnode,
1134 * finding it by name.
1135 */
1136 static void
1137 cache_purge_name(struct vnode *dvp, const char *name, size_t namelen)
1138 {
1139 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
1140 struct namecache *ncp;
1141 uint64_t key;
1142
1143 SDT_PROBE(vfs, namecache, purge, name, name, namelen, 0, 0, 0);
1144
1145 key = cache_key(name, namelen);
1146 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
1147 ncp = cache_lookup_entry(dvp, name, namelen, key);
1148 if (ncp) {
1149 cache_remove(ncp, true);
1150 }
1151 rw_exit(&dvi->vi_nc_lock);
1152 }
1153
1154 /*
1155 * Cache flush, a particular vnode; called when a vnode is renamed to
1156 * hide entries that would now be invalid.
1157 */
1158 void
1159 cache_purge1(struct vnode *vp, const char *name, size_t namelen, int flags)
1160 {
1161
1162 if (flags & PURGE_PARENTS) {
1163 cache_purge_parents(vp);
1164 }
1165 if (flags & PURGE_CHILDREN) {
1166 cache_purge_children(vp);
1167 }
1168 if (name != NULL) {
1169 cache_purge_name(vp, name, namelen);
1170 }
1171 }
1172
1173 /*
1174 * vnode filter for cache_purgevfs().
1175 */
1176 static bool
1177 cache_vdir_filter(void *cookie, vnode_t *vp)
1178 {
1179
1180 return vp->v_type == VDIR;
1181 }
1182
1183 /*
1184 * Cache flush, a whole filesystem; called when filesys is umounted to
1185 * remove entries that would now be invalid.
1186 */
1187 void
1188 cache_purgevfs(struct mount *mp)
1189 {
1190 struct vnode_iterator *iter;
1191 vnode_t *dvp;
1192
1193 vfs_vnode_iterator_init(mp, &iter);
1194 for (;;) {
1195 dvp = vfs_vnode_iterator_next(iter, cache_vdir_filter, NULL);
1196 if (dvp == NULL) {
1197 break;
1198 }
1199 cache_purge_children(dvp);
1200 vrele(dvp);
1201 }
1202 vfs_vnode_iterator_destroy(iter);
1203 }
1204
1205 /*
1206 * Re-queue an entry onto the correct LRU list, after it has scored a hit.
1207 */
1208 static void
1209 cache_activate(struct namecache *ncp)
1210 {
1211
1212 mutex_enter(&cache_lru_lock);
1213 /* Put on tail of ACTIVE list, since it just scored a hit. */
1214 TAILQ_REMOVE(&cache_lru.list[ncp->nc_lrulist], ncp, nc_lru);
1215 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
1216 cache_lru.count[ncp->nc_lrulist]--;
1217 cache_lru.count[LRU_ACTIVE]++;
1218 ncp->nc_lrulist = LRU_ACTIVE;
1219 mutex_exit(&cache_lru_lock);
1220 }
1221
1222 /*
1223 * Try to balance the LRU lists. Pick some victim entries, and re-queue
1224 * them from the head of the active list to the tail of the inactive list.
1225 */
1226 static void
1227 cache_deactivate(void)
1228 {
1229 struct namecache *ncp;
1230 int total, i;
1231
1232 KASSERT(mutex_owned(&cache_lru_lock));
1233
1234 /* If we're nowhere near budget yet, don't bother. */
1235 total = cache_lru.count[LRU_ACTIVE] + cache_lru.count[LRU_INACTIVE];
1236 if (total < (desiredvnodes >> 1)) {
1237 return;
1238 }
1239
1240 /*
1241 * Aim for a 1:1 ratio of active to inactive. This is to allow each
1242 * potential victim a reasonable amount of time to cycle through the
1243 * inactive list in order to score a hit and be reactivated, while
1244 * trying not to cause reactivations too frequently.
1245 */
1246 if (cache_lru.count[LRU_ACTIVE] < cache_lru.count[LRU_INACTIVE]) {
1247 return;
1248 }
1249
1250 /* Move only a few at a time; will catch up eventually. */
1251 for (i = 0; i < cache_lru_maxdeact; i++) {
1252 ncp = TAILQ_FIRST(&cache_lru.list[LRU_ACTIVE]);
1253 if (ncp == NULL) {
1254 break;
1255 }
1256 KASSERT(ncp->nc_lrulist == LRU_ACTIVE);
1257 ncp->nc_lrulist = LRU_INACTIVE;
1258 TAILQ_REMOVE(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
1259 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_INACTIVE], ncp, nc_lru);
1260 cache_lru.count[LRU_ACTIVE]--;
1261 cache_lru.count[LRU_INACTIVE]++;
1262 }
1263 }
1264
1265 /*
1266 * Free some entries from the cache, when we have gone over budget.
1267 *
1268 * We don't want to cause too much work for any individual caller, and it
1269 * doesn't matter if we temporarily go over budget. This is also "just a
1270 * cache" so it's not a big deal if we screw up and throw out something we
1271 * shouldn't. So we take a relaxed attitude to this process to reduce its
1272 * impact.
1273 */
1274 static void
1275 cache_reclaim(void)
1276 {
1277 struct namecache *ncp;
1278 vnode_impl_t *dvi;
1279 int toscan;
1280
1281 /*
1282 * Scan up to a preset maxium number of entries, but no more than
1283 * 0.8% of the total at once (to allow for very small systems).
1284 *
1285 * On bigger systems, do a larger chunk of work to reduce the number
1286 * of times that cache_lru_lock is held for any length of time.
1287 */
1288 mutex_enter(&cache_lru_lock);
1289 toscan = MIN(cache_lru_maxscan, desiredvnodes >> 7);
1290 toscan = MAX(toscan, 1);
1291 SDT_PROBE(vfs, namecache, prune, done, cache_lru.count[LRU_ACTIVE] +
1292 cache_lru.count[LRU_INACTIVE], toscan, 0, 0, 0);
1293 while (toscan-- != 0) {
1294 /* First try to balance the lists. */
1295 cache_deactivate();
1296
1297 /* Now look for a victim on head of inactive list (old). */
1298 ncp = TAILQ_FIRST(&cache_lru.list[LRU_INACTIVE]);
1299 if (ncp == NULL) {
1300 break;
1301 }
1302 dvi = VNODE_TO_VIMPL(ncp->nc_dvp);
1303 KASSERT(ncp->nc_lrulist == LRU_INACTIVE);
1304 KASSERT(dvi != NULL);
1305
1306 /*
1307 * Locking in the wrong direction. If we can't get the
1308 * lock, the directory is actively busy, and it could also
1309 * cause problems for the next guy in here, so send the
1310 * entry to the back of the list.
1311 */
1312 if (!rw_tryenter(&dvi->vi_nc_lock, RW_WRITER)) {
1313 TAILQ_REMOVE(&cache_lru.list[LRU_INACTIVE],
1314 ncp, nc_lru);
1315 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_INACTIVE],
1316 ncp, nc_lru);
1317 continue;
1318 }
1319
1320 /*
1321 * Now have the victim entry locked. Drop the LRU list
1322 * lock, purge the entry, and start over. The hold on
1323 * vi_nc_lock will prevent the vnode from vanishing until
1324 * finished (cache_purge() will be called on dvp before it
1325 * disappears, and that will wait on vi_nc_lock).
1326 */
1327 mutex_exit(&cache_lru_lock);
1328 cache_remove(ncp, true);
1329 rw_exit(&dvi->vi_nc_lock);
1330 mutex_enter(&cache_lru_lock);
1331 }
1332 mutex_exit(&cache_lru_lock);
1333 }
1334
1335 /*
1336 * For file system code: count a lookup that required a full re-scan of
1337 * directory metadata.
1338 */
1339 void
1340 namecache_count_pass2(void)
1341 {
1342
1343 COUNT(ncs_pass2);
1344 }
1345
1346 /*
1347 * For file system code: count a lookup that scored a hit in the directory
1348 * metadata near the location of the last lookup.
1349 */
1350 void
1351 namecache_count_2passes(void)
1352 {
1353
1354 COUNT(ncs_2passes);
1355 }
1356
1357 /*
1358 * Sum the stats from all CPUs into nchstats. This needs to run at least
1359 * once within every window where a 32-bit counter could roll over. It's
1360 * called regularly by timer to ensure this.
1361 */
1362 static void
1363 cache_update_stats(void *cookie)
1364 {
1365 CPU_INFO_ITERATOR cii;
1366 struct cpu_info *ci;
1367
1368 mutex_enter(&cache_stat_lock);
1369 for (CPU_INFO_FOREACH(cii, ci)) {
1370 struct nchcpu *nchcpu = ci->ci_data.cpu_nch;
1371 UPDATE(nchcpu, ncs_goodhits);
1372 UPDATE(nchcpu, ncs_neghits);
1373 UPDATE(nchcpu, ncs_badhits);
1374 UPDATE(nchcpu, ncs_falsehits);
1375 UPDATE(nchcpu, ncs_miss);
1376 UPDATE(nchcpu, ncs_long);
1377 UPDATE(nchcpu, ncs_pass2);
1378 UPDATE(nchcpu, ncs_2passes);
1379 UPDATE(nchcpu, ncs_revhits);
1380 UPDATE(nchcpu, ncs_revmiss);
1381 UPDATE(nchcpu, ncs_denied);
1382 }
1383 if (cookie != NULL) {
1384 memcpy(cookie, &nchstats, sizeof(nchstats));
1385 }
1386 /* Reset the timer; arrive back here in N minutes at latest. */
1387 callout_schedule(&cache_stat_callout, cache_stat_interval * hz);
1388 mutex_exit(&cache_stat_lock);
1389 }
1390
1391 /*
1392 * Fetch the current values of the stats for sysctl.
1393 */
1394 static int
1395 cache_stat_sysctl(SYSCTLFN_ARGS)
1396 {
1397 struct nchstats stats;
1398
1399 if (oldp == NULL) {
1400 *oldlenp = sizeof(nchstats);
1401 return 0;
1402 }
1403
1404 if (*oldlenp <= 0) {
1405 *oldlenp = 0;
1406 return 0;
1407 }
1408
1409 /* Refresh the global stats. */
1410 sysctl_unlock();
1411 cache_update_stats(&stats);
1412 sysctl_relock();
1413
1414 *oldlenp = MIN(sizeof(stats), *oldlenp);
1415 return sysctl_copyout(l, &stats, oldp, *oldlenp);
1416 }
1417
1418 /*
1419 * For the debugger, given the address of a vnode, print all associated
1420 * names in the cache.
1421 */
1422 #ifdef DDB
1423 void
1424 namecache_print(struct vnode *vp, void (*pr)(const char *, ...))
1425 {
1426 struct vnode *dvp = NULL;
1427 struct namecache *ncp;
1428 enum cache_lru_id id;
1429
1430 for (id = 0; id < LRU_COUNT; id++) {
1431 TAILQ_FOREACH(ncp, &cache_lru.list[id], nc_lru) {
1432 if (ncp->nc_vp == vp) {
1433 (*pr)("name %.*s\n", ncp->nc_nlen,
1434 ncp->nc_name);
1435 dvp = ncp->nc_dvp;
1436 }
1437 }
1438 }
1439 if (dvp == NULL) {
1440 (*pr)("name not found\n");
1441 return;
1442 }
1443 for (id = 0; id < LRU_COUNT; id++) {
1444 TAILQ_FOREACH(ncp, &cache_lru.list[id], nc_lru) {
1445 if (ncp->nc_vp == dvp) {
1446 (*pr)("parent %.*s\n", ncp->nc_nlen,
1447 ncp->nc_name);
1448 }
1449 }
1450 }
1451 }
1452 #endif
1453