Home | History | Annotate | Line # | Download | only in kern
vfs_cache.c revision 1.131
      1 /*	$NetBSD: vfs_cache.c,v 1.131 2020/03/23 18:41:40 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.131 2020/03/23 18:41:40 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->nc_key) == 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 #ifdef notyet
    625 bool
    626 cache_lookup_linked(struct vnode *dvp, const char *name, size_t namelen,
    627 		    struct vnode **vn_ret, krwlock_t **plock,
    628 		    kauth_cred_t cred)
    629 {
    630 	vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
    631 	struct namecache *ncp;
    632 	uint64_t key;
    633 	int error;
    634 
    635 	/* Establish default results. */
    636 	*vn_ret = NULL;
    637 
    638 	/* If disabled, or file system doesn't support this, bail out. */
    639 	if (__predict_false((dvp->v_mount->mnt_iflag & IMNT_NCLOOKUP) == 0)) {
    640 		return false;
    641 	}
    642 
    643 	if (__predict_false(namelen > cache_maxlen)) {
    644 		COUNT(ncs_long);
    645 		return false;
    646 	}
    647 
    648 	/* Compute the key up front - don't need the lock. */
    649 	key = cache_key(name, namelen);
    650 
    651 	/*
    652 	 * Acquire the directory lock.  Once we have that, we can drop the
    653 	 * previous one (if any).
    654 	 *
    655 	 * The two lock holds mean that the directory can't go away while
    656 	 * here: the directory must be purged with cache_purge() before
    657 	 * being freed, and both parent & child's vi_nc_lock must be taken
    658 	 * before that point is passed.
    659 	 *
    660 	 * However if there's no previous lock, like at the root of the
    661 	 * chain, then "dvp" must be referenced to prevent dvp going away
    662 	 * before we get its lock.
    663 	 *
    664 	 * Note that the two locks can be the same if looking up a dot, for
    665 	 * example: /usr/bin/.
    666 	 */
    667 	if (*plock != &dvi->vi_nc_lock) {
    668 		rw_enter(&dvi->vi_nc_lock, RW_READER);
    669 		if (*plock != NULL) {
    670 			rw_exit(*plock);
    671 		}
    672 		*plock = &dvi->vi_nc_lock;
    673 	} else if (*plock == NULL) {
    674 		KASSERT(dvp->v_usecount > 0);
    675 	}
    676 
    677 	/*
    678 	 * First up check if the user is allowed to look up files in this
    679 	 * directory.
    680 	 */
    681 	KASSERT(dvi->vi_nc_mode != VNOVAL && dvi->vi_nc_uid != VNOVAL &&
    682 	    dvi->vi_nc_gid != VNOVAL);
    683 	error = kauth_authorize_vnode(cred, KAUTH_ACCESS_ACTION(VEXEC,
    684 	    dvp->v_type, dvi->vi_nc_mode & ALLPERMS), dvp, NULL,
    685 	    genfs_can_access(dvp->v_type, dvi->vi_nc_mode & ALLPERMS,
    686 	    dvi->vi_nc_uid, dvi->vi_nc_gid, VEXEC, cred));
    687 	if (error != 0) {
    688 		COUNT(ncs_denied);
    689 		return false;
    690 	}
    691 
    692 	/*
    693 	 * Now look for a matching cache entry.
    694 	 */
    695 	ncp = cache_lookup_entry(dvp, name, namelen, key);
    696 	if (__predict_false(ncp == NULL)) {
    697 		COUNT(ncs_miss);
    698 		SDT_PROBE(vfs, namecache, lookup, miss, dvp,
    699 		    name, namelen, 0, 0);
    700 		return false;
    701 	}
    702 	if (ncp->nc_vp == NULL) {
    703 		/* found negative entry; vn is already null from above */
    704 		COUNT(ncs_neghits);
    705 		SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
    706 		return true;
    707 	}
    708 
    709 	COUNT(ncs_goodhits); /* XXX can be "badhits" */
    710 	SDT_PROBE(vfs, namecache, lookup, hit, dvp, name, namelen, 0, 0);
    711 
    712 	/*
    713 	 * Return with the directory lock still held.  It will either be
    714 	 * returned to us with another call to cache_lookup_linked() when
    715 	 * looking up the next component, or the caller will release it
    716 	 * manually when finished.
    717 	 */
    718 	*vn_ret = ncp->nc_vp;
    719 	return true;
    720 }
    721 #endif /* notyet */
    722 
    723 /*
    724  * Scan cache looking for name of directory entry pointing at vp.
    725  * Will not search for "." or "..".
    726  *
    727  * If the lookup succeeds the vnode is referenced and stored in dvpp.
    728  *
    729  * If bufp is non-NULL, also place the name in the buffer which starts
    730  * at bufp, immediately before *bpp, and move bpp backwards to point
    731  * at the start of it.  (Yes, this is a little baroque, but it's done
    732  * this way to cater to the whims of getcwd).
    733  *
    734  * Returns 0 on success, -1 on cache miss, positive errno on failure.
    735  */
    736 int
    737 cache_revlookup(struct vnode *vp, struct vnode **dvpp, char **bpp, char *bufp,
    738     bool checkaccess, int perms)
    739 {
    740 	vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
    741 	struct namecache *ncp;
    742 	struct vnode *dvp;
    743 	int error, nlen, lrulist;
    744 	char *bp;
    745 
    746 	KASSERT(vp != NULL);
    747 
    748 	if (cache_maxlen == 0)
    749 		goto out;
    750 
    751 	rw_enter(&vi->vi_nc_listlock, RW_READER);
    752 	if (checkaccess) {
    753 		/*
    754 		 * Check if the user is allowed to see.  NOTE: this is
    755 		 * checking for access on the "wrong" directory.  getcwd()
    756 		 * wants to see that there is access on every component
    757 		 * along the way, not that there is access to any individual
    758 		 * component.  Don't use this to check you can look in vp.
    759 		 *
    760 		 * I don't like it, I didn't come up with it, don't blame me!
    761 		 */
    762 		KASSERT(vi->vi_nc_mode != VNOVAL && vi->vi_nc_uid != VNOVAL &&
    763 		    vi->vi_nc_gid != VNOVAL);
    764 		error = kauth_authorize_vnode(curlwp->l_cred,
    765 		    KAUTH_ACCESS_ACTION(VEXEC, vp->v_type, vi->vi_nc_mode &
    766 		    ALLPERMS), vp, NULL, genfs_can_access(vp->v_type,
    767 		    vi->vi_nc_mode & ALLPERMS, vi->vi_nc_uid, vi->vi_nc_gid,
    768 		    perms, curlwp->l_cred));
    769 		    if (error != 0) {
    770 		    	rw_exit(&vi->vi_nc_listlock);
    771 			COUNT(ncs_denied);
    772 			return EACCES;
    773 		}
    774 	}
    775 	TAILQ_FOREACH(ncp, &vi->vi_nc_list, nc_list) {
    776 		KASSERT(ncp->nc_vp == vp);
    777 		KASSERT(ncp->nc_dvp != NULL);
    778 		nlen = ncp->nc_nlen;
    779 
    780 		/*
    781 		 * The queue is partially sorted.  Once we hit dots, nothing
    782 		 * else remains but dots and dotdots, so bail out.
    783 		 */
    784 		if (ncp->nc_name[0] == '.') {
    785 			if (nlen == 1 ||
    786 			    (nlen == 2 && ncp->nc_name[1] == '.')) {
    787 			    	break;
    788 			}
    789 		}
    790 
    791 		/* Record a hit on the entry.  This is an unlocked read. */
    792 		lrulist = atomic_load_relaxed(&ncp->nc_lrulist);
    793 		if (lrulist != LRU_ACTIVE) {
    794 			cache_activate(ncp);
    795 		}
    796 
    797 		if (bufp) {
    798 			bp = *bpp;
    799 			bp -= nlen;
    800 			if (bp <= bufp) {
    801 				*dvpp = NULL;
    802 				rw_exit(&vi->vi_nc_listlock);
    803 				SDT_PROBE(vfs, namecache, revlookup,
    804 				    fail, vp, ERANGE, 0, 0, 0);
    805 				return (ERANGE);
    806 			}
    807 			memcpy(bp, ncp->nc_name, nlen);
    808 			*bpp = bp;
    809 		}
    810 
    811 		dvp = ncp->nc_dvp;
    812 		mutex_enter(dvp->v_interlock);
    813 		rw_exit(&vi->vi_nc_listlock);
    814 		error = vcache_tryvget(dvp);
    815 		if (error) {
    816 			KASSERT(error == EBUSY);
    817 			if (bufp)
    818 				(*bpp) += nlen;
    819 			*dvpp = NULL;
    820 			SDT_PROBE(vfs, namecache, revlookup, fail, vp,
    821 			    error, 0, 0, 0);
    822 			return -1;
    823 		}
    824 		*dvpp = dvp;
    825 		SDT_PROBE(vfs, namecache, revlookup, success, vp, dvp,
    826 		    0, 0, 0);
    827 		COUNT(ncs_revhits);
    828 		return (0);
    829 	}
    830 	rw_exit(&vi->vi_nc_listlock);
    831 	COUNT(ncs_revmiss);
    832  out:
    833 	*dvpp = NULL;
    834 	return (-1);
    835 }
    836 
    837 /*
    838  * Add an entry to the cache.
    839  */
    840 void
    841 cache_enter(struct vnode *dvp, struct vnode *vp,
    842 	    const char *name, size_t namelen, uint32_t cnflags)
    843 {
    844 	vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
    845 	struct namecache *ncp, *oncp;
    846 	int total;
    847 
    848 	/* First, check whether we can/should add a cache entry. */
    849 	if ((cnflags & MAKEENTRY) == 0 ||
    850 	    __predict_false(namelen > cache_maxlen)) {
    851 		SDT_PROBE(vfs, namecache, enter, toolong, vp, name, namelen,
    852 		    0, 0);
    853 		return;
    854 	}
    855 
    856 	SDT_PROBE(vfs, namecache, enter, done, vp, name, namelen, 0, 0);
    857 
    858 	/*
    859 	 * Reclaim some entries if over budget.  This is an unlocked check,
    860 	 * but it doesn't matter.  Just need to catch up with things
    861 	 * eventually: it doesn't matter if we go over temporarily.
    862 	 */
    863 	total = atomic_load_relaxed(&cache_lru.count[LRU_ACTIVE]);
    864 	total += atomic_load_relaxed(&cache_lru.count[LRU_INACTIVE]);
    865 	if (__predict_false(total > desiredvnodes)) {
    866 		cache_reclaim();
    867 	}
    868 
    869 	/* Now allocate a fresh entry. */
    870 	if (__predict_true(namelen <= NCHNAMLEN)) {
    871 		ncp = pool_cache_get(cache_pool, PR_WAITOK);
    872 	} else {
    873 		size_t sz = offsetof(struct namecache, nc_name[namelen]);
    874 		ncp = kmem_alloc(sz, KM_SLEEP);
    875 	}
    876 
    877 	/*
    878 	 * Fill in cache info.  For negative hits, save the ISWHITEOUT flag
    879 	 * so we can restore it later when the cache entry is used again.
    880 	 */
    881 	ncp->nc_vp = vp;
    882 	ncp->nc_dvp = dvp;
    883 	ncp->nc_key = cache_key(name, namelen);
    884 	ncp->nc_nlen = namelen;
    885 	ncp->nc_whiteout = ((cnflags & ISWHITEOUT) != 0);
    886 	memcpy(ncp->nc_name, name, namelen);
    887 
    888 	/*
    889 	 * Insert to the directory.  Concurrent lookups may race for a cache
    890 	 * entry.  If there's a entry there already, purge it.
    891 	 */
    892 	rw_enter(&dvi->vi_nc_lock, RW_WRITER);
    893 	oncp = rb_tree_insert_node(&dvi->vi_nc_tree, ncp);
    894 	if (oncp != ncp) {
    895 		KASSERT(oncp->nc_key == ncp->nc_key);
    896 		KASSERT(oncp->nc_nlen == ncp->nc_nlen);
    897 		KASSERT(memcmp(oncp->nc_name, name, namelen) == 0);
    898 		cache_remove(oncp, true);
    899 		oncp = rb_tree_insert_node(&dvi->vi_nc_tree, ncp);
    900 		KASSERT(oncp == ncp);
    901 	}
    902 
    903 	/*
    904 	 * With the directory lock still held, insert to the tail of the
    905 	 * ACTIVE LRU list (new) and with the LRU lock held take the to
    906 	 * opportunity to incrementally balance the lists.
    907 	 */
    908 	mutex_enter(&cache_lru_lock);
    909 	ncp->nc_lrulist = LRU_ACTIVE;
    910 	cache_lru.count[LRU_ACTIVE]++;
    911 	TAILQ_INSERT_TAIL(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
    912 	cache_deactivate();
    913 	mutex_exit(&cache_lru_lock);
    914 
    915 	/*
    916 	 * Finally, insert to the vnode, and unlock.  Partially sort the
    917 	 * per-vnode list: dots go to back.
    918 	 */
    919 	if (vp != NULL) {
    920 		vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
    921 		rw_enter(&vi->vi_nc_listlock, RW_WRITER);
    922 		if ((namelen == 1 && name[0] == '.') ||
    923 		    (namelen == 2 && name[0] == '.' && name[1] == '.')) {
    924 			TAILQ_INSERT_TAIL(&vi->vi_nc_list, ncp, nc_list);
    925 		} else {
    926 			TAILQ_INSERT_HEAD(&vi->vi_nc_list, ncp, nc_list);
    927 		}
    928 		rw_exit(&vi->vi_nc_listlock);
    929 	}
    930 	rw_exit(&dvi->vi_nc_lock);
    931 }
    932 
    933 /*
    934  * Set identity info in cache for a vnode.  We only care about directories
    935  * so ignore other updates.
    936  */
    937 void
    938 cache_enter_id(struct vnode *vp, mode_t mode, uid_t uid, gid_t gid)
    939 {
    940 	vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
    941 
    942 	if (vp->v_type == VDIR) {
    943 		/* Grab both locks, for forward & reverse lookup. */
    944 		rw_enter(&vi->vi_nc_lock, RW_WRITER);
    945 		rw_enter(&vi->vi_nc_listlock, RW_WRITER);
    946 		vi->vi_nc_mode = mode;
    947 		vi->vi_nc_uid = uid;
    948 		vi->vi_nc_gid = gid;
    949 		rw_exit(&vi->vi_nc_listlock);
    950 		rw_exit(&vi->vi_nc_lock);
    951 	}
    952 }
    953 
    954 /*
    955  * Return true if we have identity for the given vnode, and use as an
    956  * opportunity to confirm that everything squares up.
    957  *
    958  * Because of shared code, some file systems could provide partial
    959  * information, missing some updates, so always check the mount flag
    960  * instead of looking for !VNOVAL.
    961  */
    962 #ifdef notyet
    963 bool
    964 cache_have_id(struct vnode *vp)
    965 {
    966 
    967 	if (vp->v_type == VDIR &&
    968 	    (vp->v_mount->mnt_iflag & IMNT_NCLOOKUP) != 0) {
    969 		KASSERT(VNODE_TO_VIMPL(vp)->vi_nc_mode != VNOVAL);
    970 		KASSERT(VNODE_TO_VIMPL(vp)->vi_nc_uid != VNOVAL);
    971 		KASSERT(VNODE_TO_VIMPL(vp)->vi_nc_gid != VNOVAL);
    972 		return true;
    973 	} else {
    974 		return false;
    975 	}
    976 }
    977 #endif /* notyet */
    978 
    979 /*
    980  * Name cache initialization, from vfs_init() when the system is booting.
    981  */
    982 void
    983 nchinit(void)
    984 {
    985 
    986 	cache_pool = pool_cache_init(sizeof(struct namecache),
    987 	    coherency_unit, 0, 0, "nchentry", NULL, IPL_NONE, NULL,
    988 	    NULL, NULL);
    989 	KASSERT(cache_pool != NULL);
    990 
    991 	mutex_init(&cache_lru_lock, MUTEX_DEFAULT, IPL_NONE);
    992 	TAILQ_INIT(&cache_lru.list[LRU_ACTIVE]);
    993 	TAILQ_INIT(&cache_lru.list[LRU_INACTIVE]);
    994 
    995 	mutex_init(&cache_stat_lock, MUTEX_DEFAULT, IPL_NONE);
    996 	callout_init(&cache_stat_callout, CALLOUT_MPSAFE);
    997 	callout_setfunc(&cache_stat_callout, cache_update_stats, NULL);
    998 	callout_schedule(&cache_stat_callout, cache_stat_interval * hz);
    999 
   1000 	KASSERT(cache_sysctllog == NULL);
   1001 	sysctl_createv(&cache_sysctllog, 0, NULL, NULL,
   1002 		       CTLFLAG_PERMANENT,
   1003 		       CTLTYPE_STRUCT, "namecache_stats",
   1004 		       SYSCTL_DESCR("namecache statistics"),
   1005 		       cache_stat_sysctl, 0, NULL, 0,
   1006 		       CTL_VFS, CTL_CREATE, CTL_EOL);
   1007 }
   1008 
   1009 /*
   1010  * Called once for each CPU in the system as attached.
   1011  */
   1012 void
   1013 cache_cpu_init(struct cpu_info *ci)
   1014 {
   1015 	void *p;
   1016 	size_t sz;
   1017 
   1018 	sz = roundup2(sizeof(struct nchstats_percpu), coherency_unit) +
   1019 	    coherency_unit;
   1020 	p = kmem_zalloc(sz, KM_SLEEP);
   1021 	ci->ci_data.cpu_nch = (void *)roundup2((uintptr_t)p, coherency_unit);
   1022 }
   1023 
   1024 /*
   1025  * A vnode is being allocated: set up cache structures.
   1026  */
   1027 void
   1028 cache_vnode_init(struct vnode *vp)
   1029 {
   1030 	vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
   1031 
   1032 	rw_init(&vi->vi_nc_lock);
   1033 	rw_init(&vi->vi_nc_listlock);
   1034 	rb_tree_init(&vi->vi_nc_tree, &cache_rbtree_ops);
   1035 	TAILQ_INIT(&vi->vi_nc_list);
   1036 	vi->vi_nc_mode = VNOVAL;
   1037 	vi->vi_nc_uid = VNOVAL;
   1038 	vi->vi_nc_gid = VNOVAL;
   1039 }
   1040 
   1041 /*
   1042  * A vnode is being freed: finish cache structures.
   1043  */
   1044 void
   1045 cache_vnode_fini(struct vnode *vp)
   1046 {
   1047 	vnode_impl_t *vi = VNODE_TO_VIMPL(vp);
   1048 
   1049 	KASSERT(RB_TREE_MIN(&vi->vi_nc_tree) == NULL);
   1050 	KASSERT(TAILQ_EMPTY(&vi->vi_nc_list));
   1051 	rw_destroy(&vi->vi_nc_lock);
   1052 	rw_destroy(&vi->vi_nc_listlock);
   1053 }
   1054 
   1055 /*
   1056  * Helper for cache_purge1(): purge cache entries for the given vnode from
   1057  * all directories that the vnode is cached in.
   1058  */
   1059 static void
   1060 cache_purge_parents(struct vnode *vp)
   1061 {
   1062 	vnode_impl_t *dvi, *vi = VNODE_TO_VIMPL(vp);
   1063 	struct vnode *dvp, *blocked;
   1064 	struct namecache *ncp;
   1065 
   1066 	SDT_PROBE(vfs, namecache, purge, parents, vp, 0, 0, 0, 0);
   1067 
   1068 	blocked = NULL;
   1069 
   1070 	rw_enter(&vi->vi_nc_listlock, RW_WRITER);
   1071 	while ((ncp = TAILQ_FIRST(&vi->vi_nc_list)) != NULL) {
   1072 		/*
   1073 		 * Locking in the wrong direction.  Try for a hold on the
   1074 		 * directory node's lock, and if we get it then all good,
   1075 		 * nuke the entry and move on to the next.
   1076 		 */
   1077 		dvp = ncp->nc_dvp;
   1078 		dvi = VNODE_TO_VIMPL(dvp);
   1079 		if (rw_tryenter(&dvi->vi_nc_lock, RW_WRITER)) {
   1080 			cache_remove(ncp, false);
   1081 			rw_exit(&dvi->vi_nc_lock);
   1082 			blocked = NULL;
   1083 			continue;
   1084 		}
   1085 
   1086 		/*
   1087 		 * We can't wait on the directory node's lock with our list
   1088 		 * lock held or the system could deadlock.
   1089 		 *
   1090 		 * Take a hold on the directory vnode to prevent it from
   1091 		 * being freed (taking the vnode & lock with it).  Then
   1092 		 * wait for the lock to become available with no other locks
   1093 		 * held, and retry.
   1094 		 *
   1095 		 * If this happens twice in a row, give the other side a
   1096 		 * breather; we can do nothing until it lets go.
   1097 		 */
   1098 		vhold(dvp);
   1099 		rw_exit(&vi->vi_nc_listlock);
   1100 		rw_enter(&dvi->vi_nc_lock, RW_WRITER);
   1101 		/* Do nothing. */
   1102 		rw_exit(&dvi->vi_nc_lock);
   1103 		holdrele(dvp);
   1104 		if (blocked == dvp) {
   1105 			kpause("ncpurge", false, 1, NULL);
   1106 		}
   1107 		rw_enter(&vi->vi_nc_listlock, RW_WRITER);
   1108 		blocked = dvp;
   1109 	}
   1110 	rw_exit(&vi->vi_nc_listlock);
   1111 }
   1112 
   1113 /*
   1114  * Helper for cache_purge1(): purge all cache entries hanging off the given
   1115  * directory vnode.
   1116  */
   1117 static void
   1118 cache_purge_children(struct vnode *dvp)
   1119 {
   1120 	vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
   1121 	struct namecache *ncp;
   1122 
   1123 	SDT_PROBE(vfs, namecache, purge, children, dvp, 0, 0, 0, 0);
   1124 
   1125 	rw_enter(&dvi->vi_nc_lock, RW_WRITER);
   1126 	for (;;) {
   1127 		ncp = rb_tree_iterate(&dvi->vi_nc_tree, NULL, RB_DIR_RIGHT);
   1128 		if (ncp == NULL) {
   1129 			break;
   1130 		}
   1131 		cache_remove(ncp, true);
   1132 	}
   1133 	rw_exit(&dvi->vi_nc_lock);
   1134 }
   1135 
   1136 /*
   1137  * Helper for cache_purge1(): purge cache entry from the given vnode,
   1138  * finding it by name.
   1139  */
   1140 static void
   1141 cache_purge_name(struct vnode *dvp, const char *name, size_t namelen)
   1142 {
   1143 	vnode_impl_t *dvi = VNODE_TO_VIMPL(dvp);
   1144 	struct namecache *ncp;
   1145 	uint64_t key;
   1146 
   1147 	SDT_PROBE(vfs, namecache, purge, name, name, namelen, 0, 0, 0);
   1148 
   1149 	key = cache_key(name, namelen);
   1150 	rw_enter(&dvi->vi_nc_lock, RW_WRITER);
   1151 	ncp = cache_lookup_entry(dvp, name, namelen, key);
   1152 	if (ncp) {
   1153 		cache_remove(ncp, true);
   1154 	}
   1155 	rw_exit(&dvi->vi_nc_lock);
   1156 }
   1157 
   1158 /*
   1159  * Cache flush, a particular vnode; called when a vnode is renamed to
   1160  * hide entries that would now be invalid.
   1161  */
   1162 void
   1163 cache_purge1(struct vnode *vp, const char *name, size_t namelen, int flags)
   1164 {
   1165 
   1166 	if (flags & PURGE_PARENTS) {
   1167 		cache_purge_parents(vp);
   1168 	}
   1169 	if (flags & PURGE_CHILDREN) {
   1170 		cache_purge_children(vp);
   1171 	}
   1172 	if (name != NULL) {
   1173 		cache_purge_name(vp, name, namelen);
   1174 	}
   1175 }
   1176 
   1177 /*
   1178  * vnode filter for cache_purgevfs().
   1179  */
   1180 static bool
   1181 cache_vdir_filter(void *cookie, vnode_t *vp)
   1182 {
   1183 
   1184 	return vp->v_type == VDIR;
   1185 }
   1186 
   1187 /*
   1188  * Cache flush, a whole filesystem; called when filesys is umounted to
   1189  * remove entries that would now be invalid.
   1190  */
   1191 void
   1192 cache_purgevfs(struct mount *mp)
   1193 {
   1194 	struct vnode_iterator *iter;
   1195 	vnode_t *dvp;
   1196 
   1197 	vfs_vnode_iterator_init(mp, &iter);
   1198 	for (;;) {
   1199 		dvp = vfs_vnode_iterator_next(iter, cache_vdir_filter, NULL);
   1200 		if (dvp == NULL) {
   1201 			break;
   1202 		}
   1203 		cache_purge_children(dvp);
   1204 		vrele(dvp);
   1205 	}
   1206 	vfs_vnode_iterator_destroy(iter);
   1207 }
   1208 
   1209 /*
   1210  * Re-queue an entry onto the correct LRU list, after it has scored a hit.
   1211  */
   1212 static void
   1213 cache_activate(struct namecache *ncp)
   1214 {
   1215 
   1216 	mutex_enter(&cache_lru_lock);
   1217 	/* Put on tail of ACTIVE list, since it just scored a hit. */
   1218 	TAILQ_REMOVE(&cache_lru.list[ncp->nc_lrulist], ncp, nc_lru);
   1219 	TAILQ_INSERT_TAIL(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
   1220 	cache_lru.count[ncp->nc_lrulist]--;
   1221 	cache_lru.count[LRU_ACTIVE]++;
   1222 	ncp->nc_lrulist = LRU_ACTIVE;
   1223 	mutex_exit(&cache_lru_lock);
   1224 }
   1225 
   1226 /*
   1227  * Try to balance the LRU lists.  Pick some victim entries, and re-queue
   1228  * them from the head of the active list to the tail of the inactive list.
   1229  */
   1230 static void
   1231 cache_deactivate(void)
   1232 {
   1233 	struct namecache *ncp;
   1234 	int total, i;
   1235 
   1236 	KASSERT(mutex_owned(&cache_lru_lock));
   1237 
   1238 	/* If we're nowhere near budget yet, don't bother. */
   1239 	total = cache_lru.count[LRU_ACTIVE] + cache_lru.count[LRU_INACTIVE];
   1240 	if (total < (desiredvnodes >> 1)) {
   1241 	    	return;
   1242 	}
   1243 
   1244 	/*
   1245 	 * Aim for a 1:1 ratio of active to inactive.  This is to allow each
   1246 	 * potential victim a reasonable amount of time to cycle through the
   1247 	 * inactive list in order to score a hit and be reactivated, while
   1248 	 * trying not to cause reactivations too frequently.
   1249 	 */
   1250 	if (cache_lru.count[LRU_ACTIVE] < cache_lru.count[LRU_INACTIVE]) {
   1251 		return;
   1252 	}
   1253 
   1254 	/* Move only a few at a time; will catch up eventually. */
   1255 	for (i = 0; i < cache_lru_maxdeact; i++) {
   1256 		ncp = TAILQ_FIRST(&cache_lru.list[LRU_ACTIVE]);
   1257 		if (ncp == NULL) {
   1258 			break;
   1259 		}
   1260 		KASSERT(ncp->nc_lrulist == LRU_ACTIVE);
   1261 		ncp->nc_lrulist = LRU_INACTIVE;
   1262 		TAILQ_REMOVE(&cache_lru.list[LRU_ACTIVE], ncp, nc_lru);
   1263 		TAILQ_INSERT_TAIL(&cache_lru.list[LRU_INACTIVE], ncp, nc_lru);
   1264 		cache_lru.count[LRU_ACTIVE]--;
   1265 		cache_lru.count[LRU_INACTIVE]++;
   1266 	}
   1267 }
   1268 
   1269 /*
   1270  * Free some entries from the cache, when we have gone over budget.
   1271  *
   1272  * We don't want to cause too much work for any individual caller, and it
   1273  * doesn't matter if we temporarily go over budget.  This is also "just a
   1274  * cache" so it's not a big deal if we screw up and throw out something we
   1275  * shouldn't.  So we take a relaxed attitude to this process to reduce its
   1276  * impact.
   1277  */
   1278 static void
   1279 cache_reclaim(void)
   1280 {
   1281 	struct namecache *ncp;
   1282 	vnode_impl_t *dvi;
   1283 	int toscan;
   1284 
   1285 	/*
   1286 	 * Scan up to a preset maxium number of entries, but no more than
   1287 	 * 0.8% of the total at once (to allow for very small systems).
   1288 	 *
   1289 	 * On bigger systems, do a larger chunk of work to reduce the number
   1290 	 * of times that cache_lru_lock is held for any length of time.
   1291 	 */
   1292 	mutex_enter(&cache_lru_lock);
   1293 	toscan = MIN(cache_lru_maxscan, desiredvnodes >> 7);
   1294 	toscan = MAX(toscan, 1);
   1295 	SDT_PROBE(vfs, namecache, prune, done, cache_lru.count[LRU_ACTIVE] +
   1296 	    cache_lru.count[LRU_INACTIVE], toscan, 0, 0, 0);
   1297 	while (toscan-- != 0) {
   1298 		/* First try to balance the lists. */
   1299 		cache_deactivate();
   1300 
   1301 		/* Now look for a victim on head of inactive list (old). */
   1302 		ncp = TAILQ_FIRST(&cache_lru.list[LRU_INACTIVE]);
   1303 		if (ncp == NULL) {
   1304 			break;
   1305 		}
   1306 		dvi = VNODE_TO_VIMPL(ncp->nc_dvp);
   1307 		KASSERT(ncp->nc_lrulist == LRU_INACTIVE);
   1308 		KASSERT(dvi != NULL);
   1309 
   1310 		/*
   1311 		 * Locking in the wrong direction.  If we can't get the
   1312 		 * lock, the directory is actively busy, and it could also
   1313 		 * cause problems for the next guy in here, so send the
   1314 		 * entry to the back of the list.
   1315 		 */
   1316 		if (!rw_tryenter(&dvi->vi_nc_lock, RW_WRITER)) {
   1317 			TAILQ_REMOVE(&cache_lru.list[LRU_INACTIVE],
   1318 			    ncp, nc_lru);
   1319 			TAILQ_INSERT_TAIL(&cache_lru.list[LRU_INACTIVE],
   1320 			    ncp, nc_lru);
   1321 			continue;
   1322 		}
   1323 
   1324 		/*
   1325 		 * Now have the victim entry locked.  Drop the LRU list
   1326 		 * lock, purge the entry, and start over.  The hold on
   1327 		 * vi_nc_lock will prevent the vnode from vanishing until
   1328 		 * finished (cache_purge() will be called on dvp before it
   1329 		 * disappears, and that will wait on vi_nc_lock).
   1330 		 */
   1331 		mutex_exit(&cache_lru_lock);
   1332 		cache_remove(ncp, true);
   1333 		rw_exit(&dvi->vi_nc_lock);
   1334 		mutex_enter(&cache_lru_lock);
   1335 	}
   1336 	mutex_exit(&cache_lru_lock);
   1337 }
   1338 
   1339 /*
   1340  * For file system code: count a lookup that required a full re-scan of
   1341  * directory metadata.
   1342  */
   1343 void
   1344 namecache_count_pass2(void)
   1345 {
   1346 
   1347 	COUNT(ncs_pass2);
   1348 }
   1349 
   1350 /*
   1351  * For file system code: count a lookup that scored a hit in the directory
   1352  * metadata near the location of the last lookup.
   1353  */
   1354 void
   1355 namecache_count_2passes(void)
   1356 {
   1357 
   1358 	COUNT(ncs_2passes);
   1359 }
   1360 
   1361 /*
   1362  * Sum the stats from all CPUs into nchstats.  This needs to run at least
   1363  * once within every window where a 32-bit counter could roll over.  It's
   1364  * called regularly by timer to ensure this.
   1365  */
   1366 static void
   1367 cache_update_stats(void *cookie)
   1368 {
   1369 	CPU_INFO_ITERATOR cii;
   1370 	struct cpu_info *ci;
   1371 
   1372 	mutex_enter(&cache_stat_lock);
   1373 	for (CPU_INFO_FOREACH(cii, ci)) {
   1374 		struct nchcpu *nchcpu = ci->ci_data.cpu_nch;
   1375 		UPDATE(nchcpu, ncs_goodhits);
   1376 		UPDATE(nchcpu, ncs_neghits);
   1377 		UPDATE(nchcpu, ncs_badhits);
   1378 		UPDATE(nchcpu, ncs_falsehits);
   1379 		UPDATE(nchcpu, ncs_miss);
   1380 		UPDATE(nchcpu, ncs_long);
   1381 		UPDATE(nchcpu, ncs_pass2);
   1382 		UPDATE(nchcpu, ncs_2passes);
   1383 		UPDATE(nchcpu, ncs_revhits);
   1384 		UPDATE(nchcpu, ncs_revmiss);
   1385 		UPDATE(nchcpu, ncs_denied);
   1386 	}
   1387 	if (cookie != NULL) {
   1388 		memcpy(cookie, &nchstats, sizeof(nchstats));
   1389 	}
   1390 	/* Reset the timer; arrive back here in N minutes at latest. */
   1391 	callout_schedule(&cache_stat_callout, cache_stat_interval * hz);
   1392 	mutex_exit(&cache_stat_lock);
   1393 }
   1394 
   1395 /*
   1396  * Fetch the current values of the stats for sysctl.
   1397  */
   1398 static int
   1399 cache_stat_sysctl(SYSCTLFN_ARGS)
   1400 {
   1401 	struct nchstats stats;
   1402 
   1403 	if (oldp == NULL) {
   1404 		*oldlenp = sizeof(nchstats);
   1405 		return 0;
   1406 	}
   1407 
   1408 	if (*oldlenp <= 0) {
   1409 		*oldlenp = 0;
   1410 		return 0;
   1411 	}
   1412 
   1413 	/* Refresh the global stats. */
   1414 	sysctl_unlock();
   1415 	cache_update_stats(&stats);
   1416 	sysctl_relock();
   1417 
   1418 	*oldlenp = MIN(sizeof(stats), *oldlenp);
   1419 	return sysctl_copyout(l, &stats, oldp, *oldlenp);
   1420 }
   1421 
   1422 /*
   1423  * For the debugger, given the address of a vnode, print all associated
   1424  * names in the cache.
   1425  */
   1426 #ifdef DDB
   1427 void
   1428 namecache_print(struct vnode *vp, void (*pr)(const char *, ...))
   1429 {
   1430 	struct vnode *dvp = NULL;
   1431 	struct namecache *ncp;
   1432 	enum cache_lru_id id;
   1433 
   1434 	for (id = 0; id < LRU_COUNT; id++) {
   1435 		TAILQ_FOREACH(ncp, &cache_lru.list[id], nc_lru) {
   1436 			if (ncp->nc_vp == vp) {
   1437 				(*pr)("name %.*s\n", ncp->nc_nlen,
   1438 				    ncp->nc_name);
   1439 				dvp = ncp->nc_dvp;
   1440 			}
   1441 		}
   1442 	}
   1443 	if (dvp == NULL) {
   1444 		(*pr)("name not found\n");
   1445 		return;
   1446 	}
   1447 	for (id = 0; id < LRU_COUNT; id++) {
   1448 		TAILQ_FOREACH(ncp, &cache_lru.list[id], nc_lru) {
   1449 			if (ncp->nc_vp == dvp) {
   1450 				(*pr)("parent %.*s\n", ncp->nc_nlen,
   1451 				    ncp->nc_name);
   1452 			}
   1453 		}
   1454 	}
   1455 }
   1456 #endif
   1457