vfs_cache.c revision 1.143 1 /* $NetBSD: vfs_cache.c,v 1.143 2020/05/16 18:31:50 christos 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.143 2020/05/16 18:31:50 christos 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 += (uint32_t)(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 /*
361 * Remove from the vnode's list. This excludes cache_revlookup(),
362 * and then it's safe to remove from the LRU lists.
363 */
364 if ((vp = ncp->nc_vp) != NULL) {
365 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
366 if (__predict_true(dir2node)) {
367 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
368 TAILQ_REMOVE(&vi->vi_nc_list, ncp, nc_list);
369 rw_exit(&vi->vi_nc_listlock);
370 } else {
371 TAILQ_REMOVE(&vi->vi_nc_list, ncp, nc_list);
372 }
373 }
374
375 /* Remove from the directory's rbtree. */
376 rb_tree_remove_node(&dvi->vi_nc_tree, ncp);
377
378 /* Remove from the LRU lists. */
379 mutex_enter(&cache_lru_lock);
380 TAILQ_REMOVE(&cache_lru.list[ncp->nc_lrulist], ncp, nc_lru);
381 cache_lru.count[ncp->nc_lrulist]--;
382 mutex_exit(&cache_lru_lock);
383
384 /* Finally, free it. */
385 if (ncp->nc_nlen > NCHNAMLEN) {
386 size_t sz = offsetof(struct namecache, nc_name[ncp->nc_nlen]);
387 kmem_free(ncp, sz);
388 } else {
389 pool_cache_put(cache_pool, ncp);
390 }
391 }
392
393 /*
394 * Find a single cache entry and return it. vi_nc_lock must be held.
395 */
396 static struct namecache * __noinline
397 cache_lookup_entry(struct vnode *dvp, const char *name, size_t namelen,
398 uint64_t key)
399 {
400 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
401 struct rb_node *node = dvi->vi_nc_tree.rbt_root;
402 struct namecache *ncp;
403 int lrulist, diff;
404
405 KASSERT(rw_lock_held(&dvi->vi_nc_lock));
406
407 /*
408 * Search the RB tree for the key. This is an inlined lookup
409 * tailored for exactly what's needed here (64-bit key and so on)
410 * that is quite a bit faster than using rb_tree_find_node().
411 *
412 * For a matching key memcmp() needs to be called once to confirm
413 * that the correct name has been found. Very rarely there will be
414 * a key value collision and the search will continue.
415 */
416 for (;;) {
417 if (__predict_false(RB_SENTINEL_P(node))) {
418 return NULL;
419 }
420 ncp = (struct namecache *)node;
421 KASSERT((void *)&ncp->nc_tree == (void *)ncp);
422 KASSERT(ncp->nc_dvp == dvp);
423 if (ncp->nc_key == key) {
424 KASSERT(ncp->nc_nlen == namelen);
425 diff = memcmp(ncp->nc_name, name, namelen);
426 if (__predict_true(diff == 0)) {
427 break;
428 }
429 node = node->rb_nodes[diff < 0];
430 } else {
431 node = node->rb_nodes[ncp->nc_key < key];
432 }
433 }
434
435 /*
436 * If the entry is on the wrong LRU list, requeue it. This is an
437 * unlocked check, but it will rarely be wrong and even then there
438 * will be no harm caused.
439 */
440 lrulist = atomic_load_relaxed(&ncp->nc_lrulist);
441 if (__predict_false(lrulist != LRU_ACTIVE)) {
442 cache_activate(ncp);
443 }
444 return ncp;
445 }
446
447 /*
448 * Look for a the name in the cache. We don't do this
449 * if the segment name is long, simply so the cache can avoid
450 * holding long names (which would either waste space, or
451 * add greatly to the complexity).
452 *
453 * Lookup is called with DVP pointing to the directory to search,
454 * and CNP providing the name of the entry being sought: cn_nameptr
455 * is the name, cn_namelen is its length, and cn_flags is the flags
456 * word from the namei operation.
457 *
458 * DVP must be locked.
459 *
460 * There are three possible non-error return states:
461 * 1. Nothing was found in the cache. Nothing is known about
462 * the requested name.
463 * 2. A negative entry was found in the cache, meaning that the
464 * requested name definitely does not exist.
465 * 3. A positive entry was found in the cache, meaning that the
466 * requested name does exist and that we are providing the
467 * vnode.
468 * In these cases the results are:
469 * 1. 0 returned; VN is set to NULL.
470 * 2. 1 returned; VN is set to NULL.
471 * 3. 1 returned; VN is set to the vnode found.
472 *
473 * The additional result argument ISWHT is set to zero, unless a
474 * negative entry is found that was entered as a whiteout, in which
475 * case ISWHT is set to one.
476 *
477 * The ISWHT_RET argument pointer may be null. In this case an
478 * assertion is made that the whiteout flag is not set. File systems
479 * that do not support whiteouts can/should do this.
480 *
481 * Filesystems that do support whiteouts should add ISWHITEOUT to
482 * cnp->cn_flags if ISWHT comes back nonzero.
483 *
484 * When a vnode is returned, it is locked, as per the vnode lookup
485 * locking protocol.
486 *
487 * There is no way for this function to fail, in the sense of
488 * generating an error that requires aborting the namei operation.
489 *
490 * (Prior to October 2012, this function returned an integer status,
491 * and a vnode, and mucked with the flags word in CNP for whiteouts.
492 * The integer status was -1 for "nothing found", ENOENT for "a
493 * negative entry found", 0 for "a positive entry found", and possibly
494 * other errors, and the value of VN might or might not have been set
495 * depending on what error occurred.)
496 */
497 bool
498 cache_lookup(struct vnode *dvp, const char *name, size_t namelen,
499 uint32_t nameiop, uint32_t cnflags,
500 int *iswht_ret, struct vnode **vn_ret)
501 {
502 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
503 struct namecache *ncp;
504 struct vnode *vp;
505 uint64_t key;
506 int error;
507 bool hit;
508 krw_t op;
509
510 /* Establish default result values */
511 if (iswht_ret != NULL) {
512 *iswht_ret = 0;
513 }
514 *vn_ret = NULL;
515
516 if (__predict_false(namelen > cache_maxlen)) {
517 SDT_PROBE(vfs, namecache, lookup, toolong, dvp,
518 name, namelen, 0, 0);
519 COUNT(ncs_long);
520 return false;
521 }
522
523 /* Compute the key up front - don't need the lock. */
524 key = cache_key(name, namelen);
525
526 /* Could the entry be purged below? */
527 if ((cnflags & ISLASTCN) != 0 &&
528 ((cnflags & MAKEENTRY) == 0 || nameiop == CREATE)) {
529 op = RW_WRITER;
530 } else {
531 op = RW_READER;
532 }
533
534 /* Now look for the name. */
535 rw_enter(&dvi->vi_nc_lock, op);
536 ncp = cache_lookup_entry(dvp, name, namelen, key);
537 if (__predict_false(ncp == NULL)) {
538 rw_exit(&dvi->vi_nc_lock);
539 COUNT(ncs_miss);
540 SDT_PROBE(vfs, namecache, lookup, miss, dvp,
541 name, namelen, 0, 0);
542 return false;
543 }
544 if (__predict_false((cnflags & MAKEENTRY) == 0)) {
545 /*
546 * Last component and we are renaming or deleting,
547 * the cache entry is invalid, or otherwise don't
548 * want cache entry to exist.
549 */
550 KASSERT((cnflags & ISLASTCN) != 0);
551 cache_remove(ncp, true);
552 rw_exit(&dvi->vi_nc_lock);
553 COUNT(ncs_badhits);
554 return false;
555 }
556 if (ncp->nc_vp == NULL) {
557 if (iswht_ret != NULL) {
558 /*
559 * Restore the ISWHITEOUT flag saved earlier.
560 */
561 *iswht_ret = ncp->nc_whiteout;
562 } else {
563 KASSERT(!ncp->nc_whiteout);
564 }
565 if (nameiop == CREATE && (cnflags & ISLASTCN) != 0) {
566 /*
567 * Last component and we are preparing to create
568 * the named object, so flush the negative cache
569 * entry.
570 */
571 COUNT(ncs_badhits);
572 cache_remove(ncp, true);
573 hit = false;
574 } else {
575 COUNT(ncs_neghits);
576 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name,
577 namelen, 0, 0);
578 /* found neg entry; vn is already null from above */
579 hit = true;
580 }
581 rw_exit(&dvi->vi_nc_lock);
582 return hit;
583 }
584 vp = ncp->nc_vp;
585 mutex_enter(vp->v_interlock);
586 rw_exit(&dvi->vi_nc_lock);
587
588 /*
589 * Unlocked except for the vnode interlock. Call vcache_tryvget().
590 */
591 error = vcache_tryvget(vp);
592 if (error) {
593 KASSERT(error == EBUSY);
594 /*
595 * This vnode is being cleaned out.
596 * XXX badhits?
597 */
598 COUNT(ncs_falsehits);
599 return false;
600 }
601
602 COUNT(ncs_goodhits);
603 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
604 /* found it */
605 *vn_ret = vp;
606 return true;
607 }
608
609 /*
610 * Version of the above without the nameiop argument, for NFS.
611 */
612 bool
613 cache_lookup_raw(struct vnode *dvp, const char *name, size_t namelen,
614 uint32_t cnflags,
615 int *iswht_ret, struct vnode **vn_ret)
616 {
617
618 return cache_lookup(dvp, name, namelen, LOOKUP, cnflags | MAKEENTRY,
619 iswht_ret, vn_ret);
620 }
621
622 /*
623 * Used by namei() to walk down a path, component by component by looking up
624 * names in the cache. The node locks are chained along the way: a parent's
625 * lock is not dropped until the child's is acquired.
626 */
627 bool
628 cache_lookup_linked(struct vnode *dvp, const char *name, size_t namelen,
629 struct vnode **vn_ret, krwlock_t **plock,
630 kauth_cred_t cred)
631 {
632 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
633 struct namecache *ncp;
634 uint64_t key;
635 int error;
636
637 /* Establish default results. */
638 *vn_ret = NULL;
639
640 /* If disabled, or file system doesn't support this, bail out. */
641 if (__predict_false((dvp->v_mount->mnt_iflag & IMNT_NCLOOKUP) == 0)) {
642 return false;
643 }
644
645 if (__predict_false(namelen > cache_maxlen)) {
646 COUNT(ncs_long);
647 return false;
648 }
649
650 /* Compute the key up front - don't need the lock. */
651 key = cache_key(name, namelen);
652
653 /*
654 * Acquire the directory lock. Once we have that, we can drop the
655 * previous one (if any).
656 *
657 * The two lock holds mean that the directory can't go away while
658 * here: the directory must be purged with cache_purge() before
659 * being freed, and both parent & child's vi_nc_lock must be taken
660 * before that point is passed.
661 *
662 * However if there's no previous lock, like at the root of the
663 * chain, then "dvp" must be referenced to prevent dvp going away
664 * before we get its lock.
665 *
666 * Note that the two locks can be the same if looking up a dot, for
667 * example: /usr/bin/. If looking up the parent (..) we can't wait
668 * on the lock as child -> parent is the wrong direction.
669 */
670 if (*plock != &dvi->vi_nc_lock) {
671 if (!rw_tryenter(&dvi->vi_nc_lock, RW_READER)) {
672 return false;
673 }
674 if (*plock != NULL) {
675 rw_exit(*plock);
676 }
677 *plock = &dvi->vi_nc_lock;
678 } else if (*plock == NULL) {
679 KASSERT(vrefcnt(dvp) > 0);
680 }
681
682 /*
683 * First up check if the user is allowed to look up files in this
684 * directory.
685 */
686 if (dvi->vi_nc_mode == VNOVAL) {
687 return false;
688 }
689 KASSERT(dvi->vi_nc_uid != VNOVAL && dvi->vi_nc_gid != VNOVAL);
690 error = kauth_authorize_vnode(cred, KAUTH_ACCESS_ACTION(VEXEC,
691 dvp->v_type, dvi->vi_nc_mode & ALLPERMS), dvp, NULL,
692 genfs_can_access(dvp, cred, dvi->vi_nc_uid, dvi->vi_nc_gid,
693 dvi->vi_nc_mode & ALLPERMS, NULL, VEXEC));
694 if (error != 0) {
695 COUNT(ncs_denied);
696 return false;
697 }
698
699 /*
700 * Now look for a matching cache entry.
701 */
702 ncp = cache_lookup_entry(dvp, name, namelen, key);
703 if (__predict_false(ncp == NULL)) {
704 COUNT(ncs_miss);
705 SDT_PROBE(vfs, namecache, lookup, miss, dvp,
706 name, namelen, 0, 0);
707 return false;
708 }
709 if (ncp->nc_vp == NULL) {
710 /* found negative entry; vn is already null from above */
711 COUNT(ncs_neghits);
712 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
713 return true;
714 }
715
716 COUNT(ncs_goodhits); /* XXX can be "badhits" */
717 SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
718
719 /*
720 * Return with the directory lock still held. It will either be
721 * returned to us with another call to cache_lookup_linked() when
722 * looking up the next component, or the caller will release it
723 * manually when finished.
724 */
725 *vn_ret = ncp->nc_vp;
726 return true;
727 }
728
729 /*
730 * Scan cache looking for name of directory entry pointing at vp.
731 * Will not search for "." or "..".
732 *
733 * If the lookup succeeds the vnode is referenced and stored in dvpp.
734 *
735 * If bufp is non-NULL, also place the name in the buffer which starts
736 * at bufp, immediately before *bpp, and move bpp backwards to point
737 * at the start of it. (Yes, this is a little baroque, but it's done
738 * this way to cater to the whims of getcwd).
739 *
740 * Returns 0 on success, -1 on cache miss, positive errno on failure.
741 */
742 int
743 cache_revlookup(struct vnode *vp, struct vnode **dvpp, char **bpp, char *bufp,
744 bool checkaccess, accmode_t accmode)
745 {
746 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
747 struct namecache *ncp;
748 struct vnode *dvp;
749 int error, nlen, lrulist;
750 char *bp;
751
752 KASSERT(vp != NULL);
753
754 if (cache_maxlen == 0)
755 goto out;
756
757 rw_enter(&vi->vi_nc_listlock, RW_READER);
758 if (checkaccess) {
759 /*
760 * Check if the user is allowed to see. NOTE: this is
761 * checking for access on the "wrong" directory. getcwd()
762 * wants to see that there is access on every component
763 * along the way, not that there is access to any individual
764 * component. Don't use this to check you can look in vp.
765 *
766 * I don't like it, I didn't come up with it, don't blame me!
767 */
768 if (vi->vi_nc_mode == VNOVAL) {
769 rw_exit(&vi->vi_nc_listlock);
770 return -1;
771 }
772 KASSERT(vi->vi_nc_uid != VNOVAL && vi->vi_nc_gid != VNOVAL);
773 error = kauth_authorize_vnode(curlwp->l_cred,
774 KAUTH_ACCESS_ACTION(VEXEC, vp->v_type, vi->vi_nc_mode &
775 ALLPERMS), vp, NULL, genfs_can_access(vp, curlwp->l_cred,
776 vi->vi_nc_uid, vi->vi_nc_gid, vi->vi_nc_mode & ALLPERMS,
777 NULL, accmode));
778 if (error != 0) {
779 rw_exit(&vi->vi_nc_listlock);
780 COUNT(ncs_denied);
781 return EACCES;
782 }
783 }
784 TAILQ_FOREACH(ncp, &vi->vi_nc_list, nc_list) {
785 KASSERT(ncp->nc_vp == vp);
786 KASSERT(ncp->nc_dvp != NULL);
787 nlen = ncp->nc_nlen;
788
789 /*
790 * The queue is partially sorted. Once we hit dots, nothing
791 * else remains but dots and dotdots, so bail out.
792 */
793 if (ncp->nc_name[0] == '.') {
794 if (nlen == 1 ||
795 (nlen == 2 && ncp->nc_name[1] == '.')) {
796 break;
797 }
798 }
799
800 /*
801 * Record a hit on the entry. This is an unlocked read but
802 * even if wrong it doesn't matter too much.
803 */
804 lrulist = atomic_load_relaxed(&ncp->nc_lrulist);
805 if (lrulist != LRU_ACTIVE) {
806 cache_activate(ncp);
807 }
808
809 if (bufp) {
810 bp = *bpp;
811 bp -= nlen;
812 if (bp <= bufp) {
813 *dvpp = NULL;
814 rw_exit(&vi->vi_nc_listlock);
815 SDT_PROBE(vfs, namecache, revlookup,
816 fail, vp, ERANGE, 0, 0, 0);
817 return (ERANGE);
818 }
819 memcpy(bp, ncp->nc_name, nlen);
820 *bpp = bp;
821 }
822
823 dvp = ncp->nc_dvp;
824 mutex_enter(dvp->v_interlock);
825 rw_exit(&vi->vi_nc_listlock);
826 error = vcache_tryvget(dvp);
827 if (error) {
828 KASSERT(error == EBUSY);
829 if (bufp)
830 (*bpp) += nlen;
831 *dvpp = NULL;
832 SDT_PROBE(vfs, namecache, revlookup, fail, vp,
833 error, 0, 0, 0);
834 return -1;
835 }
836 *dvpp = dvp;
837 SDT_PROBE(vfs, namecache, revlookup, success, vp, dvp,
838 0, 0, 0);
839 COUNT(ncs_revhits);
840 return (0);
841 }
842 rw_exit(&vi->vi_nc_listlock);
843 COUNT(ncs_revmiss);
844 out:
845 *dvpp = NULL;
846 return (-1);
847 }
848
849 /*
850 * Add an entry to the cache.
851 */
852 void
853 cache_enter(struct vnode *dvp, struct vnode *vp,
854 const char *name, size_t namelen, uint32_t cnflags)
855 {
856 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
857 struct namecache *ncp, *oncp;
858 int total;
859
860 /* First, check whether we can/should add a cache entry. */
861 if ((cnflags & MAKEENTRY) == 0 ||
862 __predict_false(namelen > cache_maxlen)) {
863 SDT_PROBE(vfs, namecache, enter, toolong, vp, name, namelen,
864 0, 0);
865 return;
866 }
867
868 SDT_PROBE(vfs, namecache, enter, done, vp, name, namelen, 0, 0);
869
870 /*
871 * Reclaim some entries if over budget. This is an unlocked check,
872 * but it doesn't matter. Just need to catch up with things
873 * eventually: it doesn't matter if we go over temporarily.
874 */
875 total = atomic_load_relaxed(&cache_lru.count[LRU_ACTIVE]);
876 total += atomic_load_relaxed(&cache_lru.count[LRU_INACTIVE]);
877 if (__predict_false(total > desiredvnodes)) {
878 cache_reclaim();
879 }
880
881 /* Now allocate a fresh entry. */
882 if (__predict_true(namelen <= NCHNAMLEN)) {
883 ncp = pool_cache_get(cache_pool, PR_WAITOK);
884 } else {
885 size_t sz = offsetof(struct namecache, nc_name[namelen]);
886 ncp = kmem_alloc(sz, KM_SLEEP);
887 }
888
889 /*
890 * Fill in cache info. For negative hits, save the ISWHITEOUT flag
891 * so we can restore it later when the cache entry is used again.
892 */
893 ncp->nc_vp = vp;
894 ncp->nc_dvp = dvp;
895 ncp->nc_key = cache_key(name, namelen);
896 ncp->nc_nlen = namelen;
897 ncp->nc_whiteout = ((cnflags & ISWHITEOUT) != 0);
898 memcpy(ncp->nc_name, name, namelen);
899
900 /*
901 * Insert to the directory. Concurrent lookups may race for a cache
902 * entry. If there's a entry there already, purge it.
903 */
904 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
905 oncp = rb_tree_insert_node(&dvi->vi_nc_tree, ncp);
906 if (oncp != ncp) {
907 KASSERT(oncp->nc_key == ncp->nc_key);
908 KASSERT(oncp->nc_nlen == ncp->nc_nlen);
909 KASSERT(memcmp(oncp->nc_name, name, namelen) == 0);
910 cache_remove(oncp, true);
911 oncp = rb_tree_insert_node(&dvi->vi_nc_tree, ncp);
912 KASSERT(oncp == ncp);
913 }
914
915 /*
916 * With the directory lock still held, insert to the tail of the
917 * ACTIVE LRU list (new) and take the opportunity to incrementally
918 * balance the lists.
919 */
920 mutex_enter(&cache_lru_lock);
921 ncp->nc_lrulist = LRU_ACTIVE;
922 cache_lru.count[LRU_ACTIVE]++;
923 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
924 cache_deactivate();
925 mutex_exit(&cache_lru_lock);
926
927 /*
928 * Finally, insert to the vnode and unlock. With everything set up
929 * it's safe to let cache_revlookup() see the entry. Partially sort
930 * the per-vnode list: dots go to back so cache_revlookup() doesn't
931 * have to consider them.
932 */
933 if (vp != NULL) {
934 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
935 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
936 if ((namelen == 1 && name[0] == '.') ||
937 (namelen == 2 && name[0] == '.' && name[1] == '.')) {
938 TAILQ_INSERT_TAIL(&vi->vi_nc_list, ncp, nc_list);
939 } else {
940 TAILQ_INSERT_HEAD(&vi->vi_nc_list, ncp, nc_list);
941 }
942 rw_exit(&vi->vi_nc_listlock);
943 }
944 rw_exit(&dvi->vi_nc_lock);
945 }
946
947 /*
948 * Set identity info in cache for a vnode. We only care about directories
949 * so ignore other updates. The cached info may be marked invalid if the
950 * inode has an ACL.
951 */
952 void
953 cache_enter_id(struct vnode *vp, mode_t mode, uid_t uid, gid_t gid, bool valid)
954 {
955 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
956
957 if (vp->v_type == VDIR) {
958 /* Grab both locks, for forward & reverse lookup. */
959 rw_enter(&vi->vi_nc_lock, RW_WRITER);
960 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
961 if (valid) {
962 vi->vi_nc_mode = mode;
963 vi->vi_nc_uid = uid;
964 vi->vi_nc_gid = gid;
965 } else {
966 vi->vi_nc_mode = VNOVAL;
967 vi->vi_nc_uid = VNOVAL;
968 vi->vi_nc_gid = VNOVAL;
969 }
970 rw_exit(&vi->vi_nc_listlock);
971 rw_exit(&vi->vi_nc_lock);
972 }
973 }
974
975 /*
976 * Return true if we have identity for the given vnode, and use as an
977 * opportunity to confirm that everything squares up.
978 *
979 * Because of shared code, some file systems could provide partial
980 * information, missing some updates, so check the mount flag too.
981 */
982 bool
983 cache_have_id(struct vnode *vp)
984 {
985
986 if (vp->v_type == VDIR &&
987 (vp->v_mount->mnt_iflag & IMNT_NCLOOKUP) != 0 &&
988 atomic_load_relaxed(&VNODE_TO_VIMPL(vp)->vi_nc_mode) != VNOVAL) {
989 return true;
990 } else {
991 return false;
992 }
993 }
994
995 /*
996 * Name cache initialization, from vfs_init() when the system is booting.
997 */
998 void
999 nchinit(void)
1000 {
1001
1002 cache_pool = pool_cache_init(sizeof(struct namecache),
1003 coherency_unit, 0, 0, "namecache", NULL, IPL_NONE, NULL,
1004 NULL, NULL);
1005 KASSERT(cache_pool != NULL);
1006
1007 mutex_init(&cache_lru_lock, MUTEX_DEFAULT, IPL_NONE);
1008 TAILQ_INIT(&cache_lru.list[LRU_ACTIVE]);
1009 TAILQ_INIT(&cache_lru.list[LRU_INACTIVE]);
1010
1011 mutex_init(&cache_stat_lock, MUTEX_DEFAULT, IPL_NONE);
1012 callout_init(&cache_stat_callout, CALLOUT_MPSAFE);
1013 callout_setfunc(&cache_stat_callout, cache_update_stats, NULL);
1014 callout_schedule(&cache_stat_callout, cache_stat_interval * hz);
1015
1016 KASSERT(cache_sysctllog == NULL);
1017 sysctl_createv(&cache_sysctllog, 0, NULL, NULL,
1018 CTLFLAG_PERMANENT,
1019 CTLTYPE_STRUCT, "namecache_stats",
1020 SYSCTL_DESCR("namecache statistics"),
1021 cache_stat_sysctl, 0, NULL, 0,
1022 CTL_VFS, CTL_CREATE, CTL_EOL);
1023 }
1024
1025 /*
1026 * Called once for each CPU in the system as attached.
1027 */
1028 void
1029 cache_cpu_init(struct cpu_info *ci)
1030 {
1031 void *p;
1032 size_t sz;
1033
1034 sz = roundup2(sizeof(struct nchstats_percpu), coherency_unit) +
1035 coherency_unit;
1036 p = kmem_zalloc(sz, KM_SLEEP);
1037 ci->ci_data.cpu_nch = (void *)roundup2((uintptr_t)p, coherency_unit);
1038 }
1039
1040 /*
1041 * A vnode is being allocated: set up cache structures.
1042 */
1043 void
1044 cache_vnode_init(struct vnode *vp)
1045 {
1046 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
1047
1048 rw_init(&vi->vi_nc_lock);
1049 rw_init(&vi->vi_nc_listlock);
1050 rb_tree_init(&vi->vi_nc_tree, &cache_rbtree_ops);
1051 TAILQ_INIT(&vi->vi_nc_list);
1052 vi->vi_nc_mode = VNOVAL;
1053 vi->vi_nc_uid = VNOVAL;
1054 vi->vi_nc_gid = VNOVAL;
1055 }
1056
1057 /*
1058 * A vnode is being freed: finish cache structures.
1059 */
1060 void
1061 cache_vnode_fini(struct vnode *vp)
1062 {
1063 vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
1064
1065 KASSERT(RB_TREE_MIN(&vi->vi_nc_tree) == NULL);
1066 KASSERT(TAILQ_EMPTY(&vi->vi_nc_list));
1067 rw_destroy(&vi->vi_nc_lock);
1068 rw_destroy(&vi->vi_nc_listlock);
1069 }
1070
1071 /*
1072 * Helper for cache_purge1(): purge cache entries for the given vnode from
1073 * all directories that the vnode is cached in.
1074 */
1075 static void
1076 cache_purge_parents(struct vnode *vp)
1077 {
1078 vnode_impl_t *dvi, *vi = VNODE_TO_VIMPL(vp);
1079 struct vnode *dvp, *blocked;
1080 struct namecache *ncp;
1081
1082 SDT_PROBE(vfs, namecache, purge, parents, vp, 0, 0, 0, 0);
1083
1084 blocked = NULL;
1085
1086 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
1087 while ((ncp = TAILQ_FIRST(&vi->vi_nc_list)) != NULL) {
1088 /*
1089 * Locking in the wrong direction. Try for a hold on the
1090 * directory node's lock, and if we get it then all good,
1091 * nuke the entry and move on to the next.
1092 */
1093 dvp = ncp->nc_dvp;
1094 dvi = VNODE_TO_VIMPL(dvp);
1095 if (rw_tryenter(&dvi->vi_nc_lock, RW_WRITER)) {
1096 cache_remove(ncp, false);
1097 rw_exit(&dvi->vi_nc_lock);
1098 blocked = NULL;
1099 continue;
1100 }
1101
1102 /*
1103 * We can't wait on the directory node's lock with our list
1104 * lock held or the system could deadlock.
1105 *
1106 * Take a hold on the directory vnode to prevent it from
1107 * being freed (taking the vnode & lock with it). Then
1108 * wait for the lock to become available with no other locks
1109 * held, and retry.
1110 *
1111 * If this happens twice in a row, give the other side a
1112 * breather; we can do nothing until it lets go.
1113 */
1114 vhold(dvp);
1115 rw_exit(&vi->vi_nc_listlock);
1116 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
1117 /* Do nothing. */
1118 rw_exit(&dvi->vi_nc_lock);
1119 holdrele(dvp);
1120 if (blocked == dvp) {
1121 kpause("ncpurge", false, 1, NULL);
1122 }
1123 rw_enter(&vi->vi_nc_listlock, RW_WRITER);
1124 blocked = dvp;
1125 }
1126 rw_exit(&vi->vi_nc_listlock);
1127 }
1128
1129 /*
1130 * Helper for cache_purge1(): purge all cache entries hanging off the given
1131 * directory vnode.
1132 */
1133 static void
1134 cache_purge_children(struct vnode *dvp)
1135 {
1136 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
1137 struct namecache *ncp;
1138
1139 SDT_PROBE(vfs, namecache, purge, children, dvp, 0, 0, 0, 0);
1140
1141 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
1142 while ((ncp = RB_TREE_MIN(&dvi->vi_nc_tree)) != NULL) {
1143 cache_remove(ncp, true);
1144 }
1145 rw_exit(&dvi->vi_nc_lock);
1146 }
1147
1148 /*
1149 * Helper for cache_purge1(): purge cache entry from the given vnode,
1150 * finding it by name.
1151 */
1152 static void
1153 cache_purge_name(struct vnode *dvp, const char *name, size_t namelen)
1154 {
1155 vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
1156 struct namecache *ncp;
1157 uint64_t key;
1158
1159 SDT_PROBE(vfs, namecache, purge, name, name, namelen, 0, 0, 0);
1160
1161 key = cache_key(name, namelen);
1162 rw_enter(&dvi->vi_nc_lock, RW_WRITER);
1163 ncp = cache_lookup_entry(dvp, name, namelen, key);
1164 if (ncp) {
1165 cache_remove(ncp, true);
1166 }
1167 rw_exit(&dvi->vi_nc_lock);
1168 }
1169
1170 /*
1171 * Cache flush, a particular vnode; called when a vnode is renamed to
1172 * hide entries that would now be invalid.
1173 */
1174 void
1175 cache_purge1(struct vnode *vp, const char *name, size_t namelen, int flags)
1176 {
1177
1178 if (flags & PURGE_PARENTS) {
1179 cache_purge_parents(vp);
1180 }
1181 if (flags & PURGE_CHILDREN) {
1182 cache_purge_children(vp);
1183 }
1184 if (name != NULL) {
1185 cache_purge_name(vp, name, namelen);
1186 }
1187 }
1188
1189 /*
1190 * vnode filter for cache_purgevfs().
1191 */
1192 static bool
1193 cache_vdir_filter(void *cookie, vnode_t *vp)
1194 {
1195
1196 return vp->v_type == VDIR;
1197 }
1198
1199 /*
1200 * Cache flush, a whole filesystem; called when filesys is umounted to
1201 * remove entries that would now be invalid.
1202 */
1203 void
1204 cache_purgevfs(struct mount *mp)
1205 {
1206 struct vnode_iterator *iter;
1207 vnode_t *dvp;
1208
1209 vfs_vnode_iterator_init(mp, &iter);
1210 for (;;) {
1211 dvp = vfs_vnode_iterator_next(iter, cache_vdir_filter, NULL);
1212 if (dvp == NULL) {
1213 break;
1214 }
1215 cache_purge_children(dvp);
1216 vrele(dvp);
1217 }
1218 vfs_vnode_iterator_destroy(iter);
1219 }
1220
1221 /*
1222 * Re-queue an entry onto the tail of the active LRU list, after it has
1223 * scored a hit.
1224 */
1225 static void
1226 cache_activate(struct namecache *ncp)
1227 {
1228
1229 mutex_enter(&cache_lru_lock);
1230 TAILQ_REMOVE(&cache_lru.list[ncp->nc_lrulist], ncp, nc_lru);
1231 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
1232 cache_lru.count[ncp->nc_lrulist]--;
1233 cache_lru.count[LRU_ACTIVE]++;
1234 ncp->nc_lrulist = LRU_ACTIVE;
1235 mutex_exit(&cache_lru_lock);
1236 }
1237
1238 /*
1239 * Try to balance the LRU lists. Pick some victim entries, and re-queue
1240 * them from the head of the active list to the tail of the inactive list.
1241 */
1242 static void
1243 cache_deactivate(void)
1244 {
1245 struct namecache *ncp;
1246 int total, i;
1247
1248 KASSERT(mutex_owned(&cache_lru_lock));
1249
1250 /* If we're nowhere near budget yet, don't bother. */
1251 total = cache_lru.count[LRU_ACTIVE] + cache_lru.count[LRU_INACTIVE];
1252 if (total < (desiredvnodes >> 1)) {
1253 return;
1254 }
1255
1256 /*
1257 * Aim for a 1:1 ratio of active to inactive. This is to allow each
1258 * potential victim a reasonable amount of time to cycle through the
1259 * inactive list in order to score a hit and be reactivated, while
1260 * trying not to cause reactivations too frequently.
1261 */
1262 if (cache_lru.count[LRU_ACTIVE] < cache_lru.count[LRU_INACTIVE]) {
1263 return;
1264 }
1265
1266 /* Move only a few at a time; will catch up eventually. */
1267 for (i = 0; i < cache_lru_maxdeact; i++) {
1268 ncp = TAILQ_FIRST(&cache_lru.list[LRU_ACTIVE]);
1269 if (ncp == NULL) {
1270 break;
1271 }
1272 KASSERT(ncp->nc_lrulist == LRU_ACTIVE);
1273 ncp->nc_lrulist = LRU_INACTIVE;
1274 TAILQ_REMOVE(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
1275 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_INACTIVE], ncp, nc_lru);
1276 cache_lru.count[LRU_ACTIVE]--;
1277 cache_lru.count[LRU_INACTIVE]++;
1278 }
1279 }
1280
1281 /*
1282 * Free some entries from the cache, when we have gone over budget.
1283 *
1284 * We don't want to cause too much work for any individual caller, and it
1285 * doesn't matter if we temporarily go over budget. This is also "just a
1286 * cache" so it's not a big deal if we screw up and throw out something we
1287 * shouldn't. So we take a relaxed attitude to this process to reduce its
1288 * impact.
1289 */
1290 static void
1291 cache_reclaim(void)
1292 {
1293 struct namecache *ncp;
1294 vnode_impl_t *dvi;
1295 int toscan;
1296
1297 /*
1298 * Scan up to a preset maxium number of entries, but no more than
1299 * 0.8% of the total at once (to allow for very small systems).
1300 *
1301 * On bigger systems, do a larger chunk of work to reduce the number
1302 * of times that cache_lru_lock is held for any length of time.
1303 */
1304 mutex_enter(&cache_lru_lock);
1305 toscan = MIN(cache_lru_maxscan, desiredvnodes >> 7);
1306 toscan = MAX(toscan, 1);
1307 SDT_PROBE(vfs, namecache, prune, done, cache_lru.count[LRU_ACTIVE] +
1308 cache_lru.count[LRU_INACTIVE], toscan, 0, 0, 0);
1309 while (toscan-- != 0) {
1310 /* First try to balance the lists. */
1311 cache_deactivate();
1312
1313 /* Now look for a victim on head of inactive list (old). */
1314 ncp = TAILQ_FIRST(&cache_lru.list[LRU_INACTIVE]);
1315 if (ncp == NULL) {
1316 break;
1317 }
1318 dvi = VNODE_TO_VIMPL(ncp->nc_dvp);
1319 KASSERT(ncp->nc_lrulist == LRU_INACTIVE);
1320 KASSERT(dvi != NULL);
1321
1322 /*
1323 * Locking in the wrong direction. If we can't get the
1324 * lock, the directory is actively busy, and it could also
1325 * cause problems for the next guy in here, so send the
1326 * entry to the back of the list.
1327 */
1328 if (!rw_tryenter(&dvi->vi_nc_lock, RW_WRITER)) {
1329 TAILQ_REMOVE(&cache_lru.list[LRU_INACTIVE],
1330 ncp, nc_lru);
1331 TAILQ_INSERT_TAIL(&cache_lru.list[LRU_INACTIVE],
1332 ncp, nc_lru);
1333 continue;
1334 }
1335
1336 /*
1337 * Now have the victim entry locked. Drop the LRU list
1338 * lock, purge the entry, and start over. The hold on
1339 * vi_nc_lock will prevent the vnode from vanishing until
1340 * finished (cache_purge() will be called on dvp before it
1341 * disappears, and that will wait on vi_nc_lock).
1342 */
1343 mutex_exit(&cache_lru_lock);
1344 cache_remove(ncp, true);
1345 rw_exit(&dvi->vi_nc_lock);
1346 mutex_enter(&cache_lru_lock);
1347 }
1348 mutex_exit(&cache_lru_lock);
1349 }
1350
1351 /*
1352 * For file system code: count a lookup that required a full re-scan of
1353 * directory metadata.
1354 */
1355 void
1356 namecache_count_pass2(void)
1357 {
1358
1359 COUNT(ncs_pass2);
1360 }
1361
1362 /*
1363 * For file system code: count a lookup that scored a hit in the directory
1364 * metadata near the location of the last lookup.
1365 */
1366 void
1367 namecache_count_2passes(void)
1368 {
1369
1370 COUNT(ncs_2passes);
1371 }
1372
1373 /*
1374 * Sum the stats from all CPUs into nchstats. This needs to run at least
1375 * once within every window where a 32-bit counter could roll over. It's
1376 * called regularly by timer to ensure this.
1377 */
1378 static void
1379 cache_update_stats(void *cookie)
1380 {
1381 CPU_INFO_ITERATOR cii;
1382 struct cpu_info *ci;
1383
1384 mutex_enter(&cache_stat_lock);
1385 for (CPU_INFO_FOREACH(cii, ci)) {
1386 struct nchcpu *nchcpu = ci->ci_data.cpu_nch;
1387 UPDATE(nchcpu, ncs_goodhits);
1388 UPDATE(nchcpu, ncs_neghits);
1389 UPDATE(nchcpu, ncs_badhits);
1390 UPDATE(nchcpu, ncs_falsehits);
1391 UPDATE(nchcpu, ncs_miss);
1392 UPDATE(nchcpu, ncs_long);
1393 UPDATE(nchcpu, ncs_pass2);
1394 UPDATE(nchcpu, ncs_2passes);
1395 UPDATE(nchcpu, ncs_revhits);
1396 UPDATE(nchcpu, ncs_revmiss);
1397 UPDATE(nchcpu, ncs_denied);
1398 }
1399 if (cookie != NULL) {
1400 memcpy(cookie, &nchstats, sizeof(nchstats));
1401 }
1402 /* Reset the timer; arrive back here in N minutes at latest. */
1403 callout_schedule(&cache_stat_callout, cache_stat_interval * hz);
1404 mutex_exit(&cache_stat_lock);
1405 }
1406
1407 /*
1408 * Fetch the current values of the stats for sysctl.
1409 */
1410 static int
1411 cache_stat_sysctl(SYSCTLFN_ARGS)
1412 {
1413 struct nchstats stats;
1414
1415 if (oldp == NULL) {
1416 *oldlenp = sizeof(nchstats);
1417 return 0;
1418 }
1419
1420 if (*oldlenp <= 0) {
1421 *oldlenp = 0;
1422 return 0;
1423 }
1424
1425 /* Refresh the global stats. */
1426 sysctl_unlock();
1427 cache_update_stats(&stats);
1428 sysctl_relock();
1429
1430 *oldlenp = MIN(sizeof(stats), *oldlenp);
1431 return sysctl_copyout(l, &stats, oldp, *oldlenp);
1432 }
1433
1434 /*
1435 * For the debugger, given the address of a vnode, print all associated
1436 * names in the cache.
1437 */
1438 #ifdef DDB
1439 void
1440 namecache_print(struct vnode *vp, void (*pr)(const char *, ...))
1441 {
1442 struct vnode *dvp = NULL;
1443 struct namecache *ncp;
1444 enum cache_lru_id id;
1445
1446 for (id = 0; id < LRU_COUNT; id++) {
1447 TAILQ_FOREACH(ncp, &cache_lru.list[id], nc_lru) {
1448 if (ncp->nc_vp == vp) {
1449 (*pr)("name %.*s\n", ncp->nc_nlen,
1450 ncp->nc_name);
1451 dvp = ncp->nc_dvp;
1452 }
1453 }
1454 }
1455 if (dvp == NULL) {
1456 (*pr)("name not found\n");
1457 return;
1458 }
1459 for (id = 0; id < LRU_COUNT; id++) {
1460 TAILQ_FOREACH(ncp, &cache_lru.list[id], nc_lru) {
1461 if (ncp->nc_vp == dvp) {
1462 (*pr)("parent %.*s\n", ncp->nc_nlen,
1463 ncp->nc_name);
1464 }
1465 }
1466 }
1467 }
1468 #endif
1469