Home | History | Annotate | Line # | Download | only in kern
vfs_cache.c revision 1.124
      1 /*	$NetBSD: vfs_cache.c,v 1.124 2019/12/01 13:39:53 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008, 2019 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * Copyright (c) 1989, 1993
     31  *	The Regents of the University of California.  All rights reserved.
     32  *
     33  * Redistribution and use in source and binary forms, with or without
     34  * modification, are permitted provided that the following conditions
     35  * are met:
     36  * 1. Redistributions of source code must retain the above copyright
     37  *    notice, this list of conditions and the following disclaimer.
     38  * 2. Redistributions in binary form must reproduce the above copyright
     39  *    notice, this list of conditions and the following disclaimer in the
     40  *    documentation and/or other materials provided with the distribution.
     41  * 3. Neither the name of the University nor the names of its contributors
     42  *    may be used to endorse or promote products derived from this software
     43  *    without specific prior written permission.
     44  *
     45  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     55  * SUCH DAMAGE.
     56  *
     57  *	@(#)vfs_cache.c	8.3 (Berkeley) 8/22/94
     58  */
     59 
     60 #include <sys/cdefs.h>
     61 __KERNEL_RCSID(0, "$NetBSD: vfs_cache.c,v 1.124 2019/12/01 13:39:53 ad Exp $");
     62 
     63 #define __NAMECACHE_PRIVATE
     64 #ifdef _KERNEL_OPT
     65 #include "opt_ddb.h"
     66 #include "opt_dtrace.h"
     67 #include "opt_revcache.h"
     68 #endif
     69 
     70 #include <sys/param.h>
     71 #include <sys/atomic.h>
     72 #include <sys/cpu.h>
     73 #include <sys/errno.h>
     74 #include <sys/evcnt.h>
     75 #include <sys/kernel.h>
     76 #include <sys/kthread.h>
     77 #include <sys/mount.h>
     78 #include <sys/mutex.h>
     79 #include <sys/namei.h>
     80 #include <sys/pool.h>
     81 #include <sys/sdt.h>
     82 #include <sys/sysctl.h>
     83 #include <sys/systm.h>
     84 #include <sys/time.h>
     85 #include <sys/vnode_impl.h>
     86 
     87 #define NAMECACHE_ENTER_REVERSE
     88 /*
     89  * Name caching works as follows:
     90  *
     91  * Names found by directory scans are retained in a cache
     92  * for future reference.  It is managed LRU, so frequently
     93  * used names will hang around.  Cache is indexed by hash value
     94  * obtained from (dvp, name) where dvp refers to the directory
     95  * containing name.
     96  *
     97  * Upon reaching the last segment of a path, if the reference
     98  * is for DELETE, or NOCACHE is set (rewrite), and the
     99  * name is located in the cache, it will be dropped.
    100  */
    101 
    102 /*
    103  * Cache entry lifetime:
    104  *
    105  *	nonexistent
    106  *	---create---> active
    107  *	---invalidate---> queued
    108  *	---reclaim---> nonexistent.
    109  *
    110  * States:
    111  * - Nonexistent.  Cache entry does not exist.
    112  *
    113  * - Active.  cache_lookup, cache_lookup_raw, cache_revlookup can look
    114  *   up, acquire references, and hand off references to vnodes,
    115  *   e.g. via v_interlock.  Marked by nonnull ncp->nc_dvp.
    116  *
    117  * - Queued.  Pending desstruction by cache_reclaim.  Cannot be used by
    118  *   cache_lookup, cache_lookup_raw, or cache_revlookup.  May still be
    119  *   on lists.  Marked by null ncp->nc_dvp.
    120  *
    121  * Transitions:
    122  *
    123  * - Create: nonexistent--->active
    124  *
    125  *   Done by cache_enter(dvp, vp, name, namelen, cnflags), called by
    126  *   VOP_LOOKUP after the answer is found.  Allocates a struct
    127  *   namecache object, initializes it with the above fields, and
    128  *   activates it by inserting it into the forward and reverse tables.
    129  *
    130  * - Invalidate: active--->queued
    131  *
    132  *   Done by cache_invalidate.  If not already invalidated, nullify
    133  *   ncp->nc_dvp and ncp->nc_vp, and add to namecache_gc_queue.  Called,
    134  *   among various other places, in cache_lookup(dvp, name, namelen,
    135  *   nameiop, cnflags, &iswht, &vp) when MAKEENTRY is missing from
    136  *   cnflags.
    137  *
    138  * - Reclaim: queued--->nonexistent
    139  *
    140  *   Done by cache_reclaim.  Disassociate ncp from any lists it is on
    141  *   and free memory.
    142  */
    143 
    144 /*
    145  * Locking.
    146  *
    147  * L namecache_lock		Global lock for namecache table and queues.
    148  * G namecache_gc_lock		Global lock for garbage collection.
    149  * C struct nchcpu::cpu_lock	Per-CPU lock to reduce read contention.
    150  * N struct namecache::nc_lock	Per-entry lock, matching nc_vp->v_interlock.
    151  *				If nc_vp==NULL, lock is private / not shared.
    152  *
    153  * Lock order: L -> C -> N
    154  *
    155  *	Examples:
    156  *	. L->C: cache_reclaim
    157  *	. C->N: cache_lookup
    158  *	. L->N: cache_purge1, cache_revlookup
    159  *
    160  * All use serialized by namecache_lock:
    161  *
    162  *	nclruhead / struct namecache::nc_lru
    163  *	ncvhashtbl / struct namecache::nc_vhash
    164  *	struct vnode_impl::vi_dnclist / struct namecache::nc_dvlist
    165  *	struct vnode_impl::vi_nclist / struct namecache::nc_vlist
    166  *	nchstats
    167  *
    168  * - Insertion serialized by namecache_lock,
    169  * - read protected by per-CPU lock,
    170  * - insert/read ordering guaranteed by memory barriers, and
    171  * - deletion allowed only under namecache_lock, with namecache_gc_lock
    172  *   taken to chop out the garbage collection list, and *all* per-CPU locks
    173  *   observed as "unowned" at least once:
    174  *
    175  *	nchashtbl / struct namecache::nc_hash
    176  *
    177  *   The per-CPU locks exist only to reduce the probability of
    178  *   contention between readers.  We do not bind to a CPU, so
    179  *   contention is still possible.
    180  *
    181  * All use serialized by struct namecache::nc_lock:
    182  *
    183  *	struct namecache::nc_dvp
    184  *	struct namecache::nc_vp
    185  *	struct namecache::nc_hittime (*)
    186  *
    187  * All use serialized by struct namecache_gc_lock:
    188  *
    189  *	struct namecache::nc_gclist
    190  *
    191  * (*) cache_prune reads nc_hittime unlocked, since approximate is OK.
    192  *
    193  * Unlocked because stable after initialization:
    194  *
    195  *	struct namecache::nc_dvp
    196  *	struct namecache::nc_vp
    197  *	struct namecache::nc_flags
    198  *	struct namecache::nc_nlen
    199  *	struct namecache::nc_name
    200  *
    201  * Unlocked because approximation is OK:
    202  *
    203  *	struct nchcpu::cpu_stats
    204  *	struct nchcpu::cpu_stats_last
    205  *
    206  * Updates under namecache_lock or any per-CPU lock are marked with
    207  * COUNT, while updates outside those locks are marked with COUNT_UNL.
    208  *
    209  * - The theory seems to have been that you could replace COUNT_UNL by
    210  *   atomic operations -- except that doesn't help unless you also
    211  *   replace COUNT by atomic operations, because mixing atomics and
    212  *   nonatomics is a recipe for failure.
    213  * - We use 32-bit per-CPU counters and 64-bit global counters under
    214  *   the theory that 32-bit counters are less likely to be hosed by
    215  *   nonatomic increment.
    216  */
    217 
    218 /*
    219  * The comment below is preserved for posterity in case it is
    220  * important, but it is clear that everywhere the namecache_count_*()
    221  * functions are called, other cache_*() functions that take the same
    222  * locks are also called, so I can't imagine how this could be a
    223  * problem:
    224  *
    225  * N.B.: Attempting to protect COUNT_UNL() increments by taking
    226  * a per-cpu lock in the namecache_count_*() functions causes
    227  * a deadlock.  Don't do that, use atomic increments instead if
    228  * the imperfections here bug you.
    229  */
    230 
    231 /*
    232  * struct nchstats_percpu:
    233  *
    234  *	Per-CPU counters.
    235  */
    236 struct nchstats_percpu _NAMEI_CACHE_STATS(uint32_t);
    237 
    238 /*
    239  * struct nchcpu:
    240  *
    241  *	Per-CPU namecache state: lock and per-CPU counters.
    242  */
    243 struct nchcpu {
    244 	kmutex_t		cpu_lock;
    245 	struct nchstats_percpu	cpu_stats;
    246 	/* XXX maybe __cacheline_aligned would improve this? */
    247 	struct nchstats_percpu	cpu_stats_last;	/* from last sample */
    248 };
    249 
    250 /*
    251  * The type for the hash code. While the hash function generates a
    252  * u32, the hash code has historically been passed around as a u_long,
    253  * and the value is modified by xor'ing a uintptr_t, so it's not
    254  * entirely clear what the best type is. For now I'll leave it
    255  * unchanged as u_long.
    256  */
    257 
    258 typedef u_long nchash_t;
    259 
    260 /*
    261  * Structures associated with name cacheing.
    262  */
    263 
    264 static kmutex_t namecache_lock __cacheline_aligned;
    265 static pool_cache_t namecache_cache __read_mostly;
    266 static TAILQ_HEAD(, namecache) nclruhead __cacheline_aligned;
    267 
    268 static LIST_HEAD(nchashhead, namecache) *nchashtbl __read_mostly;
    269 static u_long	nchash __read_mostly;
    270 
    271 #define	NCHASH2(hash, dvp)	\
    272 	(((hash) ^ ((uintptr_t)(dvp) >> 3)) & nchash)
    273 
    274 static LIST_HEAD(ncvhashhead, namecache) *ncvhashtbl __read_mostly;
    275 static u_long	ncvhash __read_mostly;
    276 
    277 #define	NCVHASH(vp)		(((uintptr_t)(vp) >> 3) & ncvhash)
    278 
    279 /* Number of cache entries allocated. */
    280 static long	numcache __cacheline_aligned;
    281 
    282 /* Garbage collection queue and number of entries pending in it. */
    283 static kmutex_t namecache_gc_lock __cacheline_aligned;
    284 static SLIST_HEAD(namecache_gc_queue, namecache) namecache_gc_queue;
    285 static u_int	namecache_gc_pend;
    286 
    287 /* Cache effectiveness statistics.  This holds total from per-cpu stats */
    288 struct nchstats	nchstats __cacheline_aligned;
    289 
    290 /*
    291  * Macros to count an event, update the central stats with per-cpu
    292  * values and add current per-cpu increments to the subsystem total
    293  * last collected by cache_reclaim().
    294  */
    295 #define	COUNT(cpup, f)	((cpup)->cpu_stats.f++)
    296 
    297 #define	UPDATE(cpup, f) do { \
    298 	struct nchcpu *Xcpup = (cpup); \
    299 	uint32_t Xcnt = (volatile uint32_t) Xcpup->cpu_stats.f; \
    300 	nchstats.f += Xcnt - Xcpup->cpu_stats_last.f; \
    301 	Xcpup->cpu_stats_last.f = Xcnt; \
    302 } while (/* CONSTCOND */ 0)
    303 
    304 /* Do unlocked stats the same way. Use a different name to allow mind changes */
    305 #define	COUNT_UNL(cpup, f)	COUNT((cpup), f)
    306 
    307 static const int cache_lowat = 97;
    308 static const int cache_hiwat = 98;
    309 static const int cache_hottime = 5;	/* number of seconds */
    310 static int doingcache = 1;		/* 1 => enable the cache */
    311 
    312 static struct evcnt cache_ev_scan;
    313 static struct evcnt cache_ev_gc;
    314 static struct evcnt cache_ev_over;
    315 static struct evcnt cache_ev_under;
    316 static struct evcnt cache_ev_forced;
    317 
    318 static struct namecache *cache_lookup_entry(
    319     const struct vnode *, const char *, size_t);
    320 static void cache_thread(void *);
    321 static void cache_invalidate(struct namecache *);
    322 static void cache_disassociate(struct namecache *);
    323 static void cache_reclaim(void);
    324 static int cache_ctor(void *, void *, int);
    325 static void cache_dtor(void *, void *);
    326 
    327 static struct sysctllog *sysctllog;
    328 static void sysctl_cache_stat_setup(void);
    329 
    330 SDT_PROVIDER_DEFINE(vfs);
    331 
    332 SDT_PROBE_DEFINE1(vfs, namecache, invalidate, done, "struct vnode *");
    333 SDT_PROBE_DEFINE1(vfs, namecache, purge, parents, "struct vnode *");
    334 SDT_PROBE_DEFINE1(vfs, namecache, purge, children, "struct vnode *");
    335 SDT_PROBE_DEFINE2(vfs, namecache, purge, name, "char *", "size_t");
    336 SDT_PROBE_DEFINE1(vfs, namecache, purge, vfs, "struct mount *");
    337 SDT_PROBE_DEFINE3(vfs, namecache, lookup, hit, "struct vnode *",
    338     "char *", "size_t");
    339 SDT_PROBE_DEFINE3(vfs, namecache, lookup, miss, "struct vnode *",
    340     "char *", "size_t");
    341 SDT_PROBE_DEFINE3(vfs, namecache, lookup, toolong, "struct vnode *",
    342     "char *", "size_t");
    343 SDT_PROBE_DEFINE2(vfs, namecache, revlookup, success, "struct vnode *",
    344      "struct vnode *");
    345 SDT_PROBE_DEFINE2(vfs, namecache, revlookup, fail, "struct vnode *",
    346      "int");
    347 SDT_PROBE_DEFINE2(vfs, namecache, prune, done, "int", "int");
    348 SDT_PROBE_DEFINE3(vfs, namecache, enter, toolong, "struct vnode *",
    349     "char *", "size_t");
    350 SDT_PROBE_DEFINE3(vfs, namecache, enter, done, "struct vnode *",
    351     "char *", "size_t");
    352 
    353 /*
    354  * Compute the hash for an entry.
    355  *
    356  * (This is for now a wrapper around namei_hash, whose interface is
    357  * for the time being slightly inconvenient.)
    358  */
    359 static nchash_t
    360 cache_hash(const char *name, size_t namelen)
    361 {
    362 	const char *endptr;
    363 
    364 	endptr = name + namelen;
    365 	return namei_hash(name, &endptr);
    366 }
    367 
    368 /*
    369  * Invalidate a cache entry and enqueue it for garbage collection.
    370  */
    371 static void
    372 cache_invalidate(struct namecache *ncp)
    373 {
    374 
    375 	KASSERT(mutex_owned(ncp->nc_lock));
    376 
    377 	if (ncp->nc_dvp != NULL) {
    378 		SDT_PROBE(vfs, namecache, invalidate, done, ncp->nc_dvp,
    379 		    0, 0, 0, 0);
    380 
    381 		ncp->nc_vp = NULL;
    382 		ncp->nc_dvp = NULL;
    383 		mutex_enter(&namecache_gc_lock);
    384 		SLIST_INSERT_HEAD(&namecache_gc_queue, ncp, nc_gclist);
    385 		namecache_gc_pend++;
    386 		mutex_exit(&namecache_gc_lock);
    387 	}
    388 }
    389 
    390 /*
    391  * Disassociate a namecache entry from any vnodes it is attached to,
    392  * and remove from the global LRU list.
    393  */
    394 static void
    395 cache_disassociate(struct namecache *ncp)
    396 {
    397 
    398 	KASSERT(mutex_owned(&namecache_lock));
    399 	KASSERT(ncp->nc_dvp == NULL);
    400 
    401 	if (ncp->nc_lru.tqe_prev != NULL) {
    402 		TAILQ_REMOVE(&nclruhead, ncp, nc_lru);
    403 		ncp->nc_lru.tqe_prev = NULL;
    404 	}
    405 	if (ncp->nc_vhash.le_prev != NULL) {
    406 		LIST_REMOVE(ncp, nc_vhash);
    407 		ncp->nc_vhash.le_prev = NULL;
    408 	}
    409 	if (ncp->nc_vlist.le_prev != NULL) {
    410 		LIST_REMOVE(ncp, nc_vlist);
    411 		ncp->nc_vlist.le_prev = NULL;
    412 	}
    413 	if (ncp->nc_dvlist.le_prev != NULL) {
    414 		LIST_REMOVE(ncp, nc_dvlist);
    415 		ncp->nc_dvlist.le_prev = NULL;
    416 	}
    417 }
    418 
    419 /*
    420  * Lock all CPUs to prevent any cache lookup activity.  Conceptually,
    421  * this locks out all "readers".  This is a very heavyweight operation
    422  * that we only use for nchreinit().
    423  */
    424 static void
    425 cache_lock_cpus(void)
    426 {
    427 	CPU_INFO_ITERATOR cii;
    428 	struct cpu_info *ci;
    429 	struct nchcpu *cpup;
    430 
    431 	/* Not necessary but don't want more than one LWP trying this. */
    432 	KASSERT(mutex_owned(&namecache_lock));
    433 
    434 	/*
    435 	 * Lock out all CPUs first, then harvest per-cpu stats.  This
    436 	 * is probably not quite as cache-efficient as doing the lock
    437 	 * and harvest at the same time, but allows cache_stat_sysctl()
    438 	 * to make do with a per-cpu lock.
    439 	 */
    440 	for (CPU_INFO_FOREACH(cii, ci)) {
    441 		cpup = ci->ci_data.cpu_nch;
    442 		mutex_enter(&cpup->cpu_lock);
    443 	}
    444 	for (CPU_INFO_FOREACH(cii, ci)) {
    445 		cpup = ci->ci_data.cpu_nch;
    446 		UPDATE(cpup, ncs_goodhits);
    447 		UPDATE(cpup, ncs_neghits);
    448 		UPDATE(cpup, ncs_badhits);
    449 		UPDATE(cpup, ncs_falsehits);
    450 		UPDATE(cpup, ncs_miss);
    451 		UPDATE(cpup, ncs_long);
    452 		UPDATE(cpup, ncs_pass2);
    453 		UPDATE(cpup, ncs_2passes);
    454 		UPDATE(cpup, ncs_revhits);
    455 		UPDATE(cpup, ncs_revmiss);
    456 	}
    457 }
    458 
    459 /*
    460  * Release all CPU locks.
    461  */
    462 static void
    463 cache_unlock_cpus(void)
    464 {
    465 	CPU_INFO_ITERATOR cii;
    466 	struct cpu_info *ci;
    467 	struct nchcpu *cpup;
    468 
    469 	for (CPU_INFO_FOREACH(cii, ci)) {
    470 		cpup = ci->ci_data.cpu_nch;
    471 		mutex_exit(&cpup->cpu_lock);
    472 	}
    473 }
    474 
    475 /*
    476  * Find a single cache entry and return it locked.
    477  * The caller needs to hold namecache_lock or a per-cpu lock to hold
    478  * off cache_reclaim().
    479  */
    480 static struct namecache *
    481 cache_lookup_entry(const struct vnode *dvp, const char *name, size_t namelen)
    482 {
    483 	struct nchashhead *ncpp;
    484 	struct namecache *ncp;
    485 	nchash_t hash;
    486 	int ticks;
    487 
    488 	KASSERT(dvp != NULL);
    489 	hash = cache_hash(name, namelen);
    490 	ncpp = &nchashtbl[NCHASH2(hash, dvp)];
    491 
    492 	LIST_FOREACH(ncp, ncpp, nc_hash) {
    493 		membar_datadep_consumer();	/* for Alpha... */
    494 		if (ncp->nc_dvp != dvp ||
    495 		    ncp->nc_nlen != namelen ||
    496 		    memcmp(ncp->nc_name, name, (u_int)ncp->nc_nlen))
    497 		    	continue;
    498 	    	mutex_enter(ncp->nc_lock);
    499 		if (__predict_true(ncp->nc_dvp == dvp)) {
    500 			ticks = hardclock_ticks;
    501 			if (ncp->nc_hittime != ticks) {
    502 				/*
    503 				 * Avoid false sharing on MP: do not store
    504 				 * to *ncp unless the value changed.
    505 				 */
    506 				ncp->nc_hittime = ticks;
    507 			}
    508 			SDT_PROBE(vfs, namecache, lookup, hit, dvp,
    509 			    name, namelen, 0, 0);
    510 			return ncp;
    511 		}
    512 		/* Raced: entry has been nullified. */
    513 		mutex_exit(ncp->nc_lock);
    514 	}
    515 
    516 	SDT_PROBE(vfs, namecache, lookup, miss, dvp,
    517 	    name, namelen, 0, 0);
    518 	return NULL;
    519 }
    520 
    521 /*
    522  * Look for a the name in the cache. We don't do this
    523  * if the segment name is long, simply so the cache can avoid
    524  * holding long names (which would either waste space, or
    525  * add greatly to the complexity).
    526  *
    527  * Lookup is called with DVP pointing to the directory to search,
    528  * and CNP providing the name of the entry being sought: cn_nameptr
    529  * is the name, cn_namelen is its length, and cn_flags is the flags
    530  * word from the namei operation.
    531  *
    532  * DVP must be locked.
    533  *
    534  * There are three possible non-error return states:
    535  *    1. Nothing was found in the cache. Nothing is known about
    536  *       the requested name.
    537  *    2. A negative entry was found in the cache, meaning that the
    538  *       requested name definitely does not exist.
    539  *    3. A positive entry was found in the cache, meaning that the
    540  *       requested name does exist and that we are providing the
    541  *       vnode.
    542  * In these cases the results are:
    543  *    1. 0 returned; VN is set to NULL.
    544  *    2. 1 returned; VN is set to NULL.
    545  *    3. 1 returned; VN is set to the vnode found.
    546  *
    547  * The additional result argument ISWHT is set to zero, unless a
    548  * negative entry is found that was entered as a whiteout, in which
    549  * case ISWHT is set to one.
    550  *
    551  * The ISWHT_RET argument pointer may be null. In this case an
    552  * assertion is made that the whiteout flag is not set. File systems
    553  * that do not support whiteouts can/should do this.
    554  *
    555  * Filesystems that do support whiteouts should add ISWHITEOUT to
    556  * cnp->cn_flags if ISWHT comes back nonzero.
    557  *
    558  * When a vnode is returned, it is locked, as per the vnode lookup
    559  * locking protocol.
    560  *
    561  * There is no way for this function to fail, in the sense of
    562  * generating an error that requires aborting the namei operation.
    563  *
    564  * (Prior to October 2012, this function returned an integer status,
    565  * and a vnode, and mucked with the flags word in CNP for whiteouts.
    566  * The integer status was -1 for "nothing found", ENOENT for "a
    567  * negative entry found", 0 for "a positive entry found", and possibly
    568  * other errors, and the value of VN might or might not have been set
    569  * depending on what error occurred.)
    570  */
    571 bool
    572 cache_lookup(struct vnode *dvp, const char *name, size_t namelen,
    573 	     uint32_t nameiop, uint32_t cnflags,
    574 	     int *iswht_ret, struct vnode **vn_ret)
    575 {
    576 	struct namecache *ncp;
    577 	struct vnode *vp;
    578 	struct nchcpu *cpup;
    579 	int error;
    580 	bool hit;
    581 
    582 	/* Establish default result values */
    583 	if (iswht_ret != NULL) {
    584 		*iswht_ret = 0;
    585 	}
    586 	*vn_ret = NULL;
    587 
    588 	if (__predict_false(!doingcache)) {
    589 		return false;
    590 	}
    591 
    592 	cpup = curcpu()->ci_data.cpu_nch;
    593 	mutex_enter(&cpup->cpu_lock);
    594 	if (__predict_false(namelen > USHRT_MAX)) {
    595 		SDT_PROBE(vfs, namecache, lookup, toolong, dvp,
    596 		    name, namelen, 0, 0);
    597 		COUNT(cpup, ncs_long);
    598 		mutex_exit(&cpup->cpu_lock);
    599 		/* found nothing */
    600 		return false;
    601 	}
    602 
    603 	ncp = cache_lookup_entry(dvp, name, namelen);
    604 	if (__predict_false(ncp == NULL)) {
    605 		COUNT(cpup, ncs_miss);
    606 		mutex_exit(&cpup->cpu_lock);
    607 		/* found nothing */
    608 		return false;
    609 	}
    610 	if ((cnflags & MAKEENTRY) == 0) {
    611 		COUNT(cpup, ncs_badhits);
    612 		/*
    613 		 * Last component and we are renaming or deleting,
    614 		 * the cache entry is invalid, or otherwise don't
    615 		 * want cache entry to exist.
    616 		 */
    617 		cache_invalidate(ncp);
    618 		mutex_exit(ncp->nc_lock);
    619 		mutex_exit(&cpup->cpu_lock);
    620 		/* found nothing */
    621 		return false;
    622 	}
    623 	vp = ncp->nc_vp;
    624 	if (__predict_false(vp == NULL)) {
    625 		if (iswht_ret != NULL) {
    626 			/*
    627 			 * Restore the ISWHITEOUT flag saved earlier.
    628 			 */
    629 			KASSERT((ncp->nc_flags & ~ISWHITEOUT) == 0);
    630 			*iswht_ret = (ncp->nc_flags & ISWHITEOUT) != 0;
    631 		} else {
    632 			KASSERT(ncp->nc_flags == 0);
    633 		}
    634 
    635 		if (__predict_true(nameiop != CREATE ||
    636 		    (cnflags & ISLASTCN) == 0)) {
    637 			COUNT(cpup, ncs_neghits);
    638 			/* found neg entry; vn is already null from above */
    639 			hit = true;
    640 		} else {
    641 			COUNT(cpup, ncs_badhits);
    642 			/*
    643 			 * Last component and we are preparing to create
    644 			 * the named object, so flush the negative cache
    645 			 * entry.
    646 			 */
    647 			cache_invalidate(ncp);
    648 			/* found nothing */
    649 			hit = false;
    650 		}
    651 		mutex_exit(ncp->nc_lock);
    652 		mutex_exit(&cpup->cpu_lock);
    653 		return hit;
    654 	}
    655 	KASSERT(vp->v_interlock == ncp->nc_lock);
    656 	mutex_exit(&cpup->cpu_lock);
    657 
    658 	/*
    659 	 * Unlocked except for the vnode interlock.  Call vcache_tryvget().
    660 	 */
    661 	error = vcache_tryvget(vp);
    662 	if (error) {
    663 		KASSERT(error == EBUSY);
    664 		/*
    665 		 * This vnode is being cleaned out.
    666 		 * XXX badhits?
    667 		 */
    668 		COUNT_UNL(cpup, ncs_falsehits);
    669 		/* found nothing */
    670 		return false;
    671 	}
    672 
    673 	COUNT_UNL(cpup, ncs_goodhits);
    674 	/* found it */
    675 	*vn_ret = vp;
    676 	return true;
    677 }
    678 
    679 
    680 /*
    681  * Cut-'n-pasted version of the above without the nameiop argument.
    682  */
    683 bool
    684 cache_lookup_raw(struct vnode *dvp, const char *name, size_t namelen,
    685 		 uint32_t cnflags,
    686 		 int *iswht_ret, struct vnode **vn_ret)
    687 {
    688 	struct namecache *ncp;
    689 	struct vnode *vp;
    690 	struct nchcpu *cpup;
    691 	int error;
    692 
    693 	/* Establish default results. */
    694 	if (iswht_ret != NULL) {
    695 		*iswht_ret = 0;
    696 	}
    697 	*vn_ret = NULL;
    698 
    699 	if (__predict_false(!doingcache)) {
    700 		/* found nothing */
    701 		return false;
    702 	}
    703 
    704 	cpup = curcpu()->ci_data.cpu_nch;
    705 	mutex_enter(&cpup->cpu_lock);
    706 	if (__predict_false(namelen > USHRT_MAX)) {
    707 		COUNT(cpup, ncs_long);
    708 		mutex_exit(&cpup->cpu_lock);
    709 		/* found nothing */
    710 		return false;
    711 	}
    712 	ncp = cache_lookup_entry(dvp, name, namelen);
    713 	if (__predict_false(ncp == NULL)) {
    714 		COUNT(cpup, ncs_miss);
    715 		mutex_exit(&cpup->cpu_lock);
    716 		/* found nothing */
    717 		return false;
    718 	}
    719 	vp = ncp->nc_vp;
    720 	if (vp == NULL) {
    721 		/*
    722 		 * Restore the ISWHITEOUT flag saved earlier.
    723 		 */
    724 		if (iswht_ret != NULL) {
    725 			KASSERT((ncp->nc_flags & ~ISWHITEOUT) == 0);
    726 			/*cnp->cn_flags |= ncp->nc_flags;*/
    727 			*iswht_ret = (ncp->nc_flags & ISWHITEOUT) != 0;
    728 		}
    729 		COUNT(cpup, ncs_neghits);
    730 		mutex_exit(ncp->nc_lock);
    731 		mutex_exit(&cpup->cpu_lock);
    732 		/* found negative entry; vn is already null from above */
    733 		return true;
    734 	}
    735 	KASSERT(vp->v_interlock == ncp->nc_lock);
    736 	mutex_exit(&cpup->cpu_lock);
    737 
    738 	/*
    739 	 * Unlocked except for the vnode interlock.  Call vcache_tryvget().
    740 	 */
    741 	error = vcache_tryvget(vp);
    742 	if (error) {
    743 		KASSERT(error == EBUSY);
    744 		/*
    745 		 * This vnode is being cleaned out.
    746 		 * XXX badhits?
    747 		 */
    748 		COUNT_UNL(cpup, ncs_falsehits);
    749 		/* found nothing */
    750 		return false;
    751 	}
    752 
    753 	COUNT_UNL(cpup, ncs_goodhits); /* XXX can be "badhits" */
    754 	/* found it */
    755 	*vn_ret = vp;
    756 	return true;
    757 }
    758 
    759 /*
    760  * Scan cache looking for name of directory entry pointing at vp.
    761  *
    762  * If the lookup succeeds the vnode is referenced and stored in dvpp.
    763  *
    764  * If bufp is non-NULL, also place the name in the buffer which starts
    765  * at bufp, immediately before *bpp, and move bpp backwards to point
    766  * at the start of it.  (Yes, this is a little baroque, but it's done
    767  * this way to cater to the whims of getcwd).
    768  *
    769  * Returns 0 on success, -1 on cache miss, positive errno on failure.
    770  */
    771 int
    772 cache_revlookup(struct vnode *vp, struct vnode **dvpp, char **bpp, char *bufp)
    773 {
    774 	struct namecache *ncp;
    775 	struct vnode *dvp;
    776 	struct ncvhashhead *nvcpp;
    777 	struct nchcpu *cpup;
    778 	char *bp;
    779 	int error, nlen;
    780 	bool locked, again;
    781 
    782 	if (!doingcache)
    783 		goto out;
    784 
    785 	nvcpp = &ncvhashtbl[NCVHASH(vp)];
    786 
    787 	/*
    788 	 * We increment counters in the local CPU's per-cpu stats.
    789 	 * We don't take the per-cpu lock, however, since this function
    790 	 * is the only place these counters are incremented so no one
    791 	 * will be racing with us to increment them.
    792 	 */
    793 	again = false;
    794  retry:
    795 	cpup = curcpu()->ci_data.cpu_nch;
    796 	mutex_enter(&namecache_lock);
    797 	LIST_FOREACH(ncp, nvcpp, nc_vhash) {
    798 		mutex_enter(ncp->nc_lock);
    799 		if (ncp->nc_vp == vp &&
    800 		    (dvp = ncp->nc_dvp) != NULL &&
    801 		    dvp != vp) { 		/* avoid pesky . entries.. */
    802 
    803 #ifdef DIAGNOSTIC
    804 			if (ncp->nc_nlen == 1 &&
    805 			    ncp->nc_name[0] == '.')
    806 				panic("cache_revlookup: found entry for .");
    807 
    808 			if (ncp->nc_nlen == 2 &&
    809 			    ncp->nc_name[0] == '.' &&
    810 			    ncp->nc_name[1] == '.')
    811 				panic("cache_revlookup: found entry for ..");
    812 #endif
    813 			COUNT(cpup, ncs_revhits);
    814 			nlen = ncp->nc_nlen;
    815 
    816 			if (bufp) {
    817 				bp = *bpp;
    818 				bp -= nlen;
    819 				if (bp <= bufp) {
    820 					*dvpp = NULL;
    821 					mutex_exit(ncp->nc_lock);
    822 					mutex_exit(&namecache_lock);
    823 					SDT_PROBE(vfs, namecache, revlookup,
    824 					    fail, vp, ERANGE, 0, 0, 0);
    825 					return (ERANGE);
    826 				}
    827 				memcpy(bp, ncp->nc_name, nlen);
    828 				*bpp = bp;
    829 			}
    830 
    831 
    832 			KASSERT(ncp->nc_lock != dvp->v_interlock);
    833 			locked = mutex_tryenter(dvp->v_interlock);
    834 			mutex_exit(ncp->nc_lock);
    835 			mutex_exit(&namecache_lock);
    836 			if (!locked) {
    837 				if (again) {
    838 					kpause("nchrace", false, 1, NULL);
    839 				}
    840 				again = true;
    841 				goto retry;
    842 			}
    843 			error = vcache_tryvget(dvp);
    844 			if (error) {
    845 				KASSERT(error == EBUSY);
    846 				if (bufp)
    847 					(*bpp) += nlen;
    848 				*dvpp = NULL;
    849 				SDT_PROBE(vfs, namecache, revlookup, fail, vp,
    850 				    error, 0, 0, 0);
    851 				return -1;
    852 			}
    853 			*dvpp = dvp;
    854 			SDT_PROBE(vfs, namecache, revlookup, success, vp, dvp,
    855 			    0, 0, 0);
    856 			return (0);
    857 		}
    858 		mutex_exit(ncp->nc_lock);
    859 	}
    860 	COUNT(cpup, ncs_revmiss);
    861 	mutex_exit(&namecache_lock);
    862  out:
    863 	*dvpp = NULL;
    864 	return (-1);
    865 }
    866 
    867 /*
    868  * Add an entry to the cache
    869  */
    870 void
    871 cache_enter(struct vnode *dvp, struct vnode *vp,
    872 	    const char *name, size_t namelen, uint32_t cnflags)
    873 {
    874 	struct namecache *ncp;
    875 	struct namecache *oncp;
    876 	struct nchashhead *ncpp;
    877 	struct ncvhashhead *nvcpp;
    878 	nchash_t hash;
    879 
    880 	/* First, check whether we can/should add a cache entry. */
    881 	if ((cnflags & MAKEENTRY) == 0 ||
    882 	    __predict_false(namelen > USHRT_MAX || !doingcache)) {
    883 		SDT_PROBE(vfs, namecache, enter, toolong, vp, name, namelen,
    884 		    0, 0);
    885 		return;
    886 	}
    887 
    888 	SDT_PROBE(vfs, namecache, enter, done, vp, name, namelen, 0, 0);
    889 	if (numcache > desiredvnodes) {
    890 		mutex_enter(&namecache_lock);
    891 		cache_ev_forced.ev_count++;
    892 		cache_reclaim();
    893 		mutex_exit(&namecache_lock);
    894 	}
    895 
    896 	if (namelen > NCHNAMLEN) {
    897 		ncp = kmem_alloc(sizeof(*ncp) + namelen, KM_SLEEP);
    898 		cache_ctor(NULL, ncp, 0);
    899 	} else
    900 		ncp = pool_cache_get(namecache_cache, PR_WAITOK);
    901 
    902 	mutex_enter(&namecache_lock);
    903 	numcache++;
    904 
    905 	/*
    906 	 * Concurrent lookups in the same directory may race for a
    907 	 * cache entry.  if there's a duplicated entry, free it.
    908 	 */
    909 	oncp = cache_lookup_entry(dvp, name, namelen);
    910 	if (oncp) {
    911 		cache_invalidate(oncp);
    912 		mutex_exit(oncp->nc_lock);
    913 	}
    914 
    915 	/* Grab the vnode we just found. */
    916 	ncp->nc_vp = vp;
    917 	ncp->nc_flags = 0;
    918 	ncp->nc_hittime = 0;
    919 	if (vp == NULL) {
    920 		/*
    921 		 * For negative hits, save the ISWHITEOUT flag so we can
    922 		 * restore it later when the cache entry is used again.
    923 		 */
    924 		ncp->nc_flags = cnflags & ISWHITEOUT;
    925 		ncp->nc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    926 	} else {
    927 		ncp->nc_lock = vp->v_interlock;
    928 		mutex_obj_hold(ncp->nc_lock);
    929 	}
    930 
    931 	/* Fill in cache info. */
    932 	mutex_enter(ncp->nc_lock);
    933 	ncp->nc_dvp = dvp;
    934 	LIST_INSERT_HEAD(&VNODE_TO_VIMPL(dvp)->vi_dnclist, ncp, nc_dvlist);
    935 	if (vp)
    936 		LIST_INSERT_HEAD(&VNODE_TO_VIMPL(vp)->vi_nclist, ncp, nc_vlist);
    937 	else {
    938 		ncp->nc_vlist.le_prev = NULL;
    939 		ncp->nc_vlist.le_next = NULL;
    940 	}
    941 	KASSERT(namelen <= USHRT_MAX);
    942 	ncp->nc_nlen = namelen;
    943 	memcpy(ncp->nc_name, name, (unsigned)ncp->nc_nlen);
    944 	TAILQ_INSERT_TAIL(&nclruhead, ncp, nc_lru);
    945 	hash = cache_hash(name, namelen);
    946 	ncpp = &nchashtbl[NCHASH2(hash, dvp)];
    947 
    948 	/*
    949 	 * Flush updates before making visible in table.  No need for a
    950 	 * memory barrier on the other side: to see modifications the
    951 	 * list must be followed, meaning a dependent pointer load.
    952 	 * The below is LIST_INSERT_HEAD() inlined, with the memory
    953 	 * barrier included in the correct place.
    954 	 */
    955 	if ((ncp->nc_hash.le_next = ncpp->lh_first) != NULL)
    956 		ncpp->lh_first->nc_hash.le_prev = &ncp->nc_hash.le_next;
    957 	ncp->nc_hash.le_prev = &ncpp->lh_first;
    958 	membar_producer();
    959 	ncpp->lh_first = ncp;
    960 
    961 	ncp->nc_vhash.le_prev = NULL;
    962 	ncp->nc_vhash.le_next = NULL;
    963 
    964 	/*
    965 	 * Create reverse-cache entries (used in getcwd) for directories.
    966 	 * (and in linux procfs exe node)
    967 	 */
    968 	if (vp != NULL &&
    969 	    vp != dvp &&
    970 #ifndef NAMECACHE_ENTER_REVERSE
    971 	    vp->v_type == VDIR &&
    972 #endif
    973 	    (ncp->nc_nlen > 2 ||
    974 	    (ncp->nc_nlen > 1 && ncp->nc_name[1] != '.') ||
    975 	    (/* ncp->nc_nlen > 0 && */ ncp->nc_name[0] != '.'))) {
    976 		nvcpp = &ncvhashtbl[NCVHASH(vp)];
    977 		LIST_INSERT_HEAD(nvcpp, ncp, nc_vhash);
    978 	}
    979 	mutex_exit(ncp->nc_lock);
    980 	mutex_exit(&namecache_lock);
    981 }
    982 
    983 /*
    984  * Name cache initialization, from vfs_init() when we are booting
    985  */
    986 void
    987 nchinit(void)
    988 {
    989 	int error;
    990 
    991 	TAILQ_INIT(&nclruhead);
    992 	namecache_cache = pool_cache_init(sizeof(struct namecache) + NCHNAMLEN,
    993 	    coherency_unit, 0, 0, "ncache", NULL, IPL_NONE, cache_ctor,
    994 	    cache_dtor, NULL);
    995 	KASSERT(namecache_cache != NULL);
    996 
    997 	mutex_init(&namecache_lock, MUTEX_DEFAULT, IPL_NONE);
    998 	mutex_init(&namecache_gc_lock, MUTEX_DEFAULT, IPL_NONE);
    999 	nchashtbl = hashinit(desiredvnodes, HASH_LIST, true, &nchash);
   1000 	ncvhashtbl =
   1001 #ifdef NAMECACHE_ENTER_REVERSE
   1002 	    hashinit(desiredvnodes, HASH_LIST, true, &ncvhash);
   1003 #else
   1004 	    hashinit(desiredvnodes/8, HASH_LIST, true, &ncvhash);
   1005 #endif
   1006 
   1007 	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, cache_thread,
   1008 	    NULL, NULL, "cachegc");
   1009 	if (error != 0)
   1010 		panic("nchinit %d", error);
   1011 
   1012 	evcnt_attach_dynamic(&cache_ev_scan, EVCNT_TYPE_MISC, NULL,
   1013 	   "namecache", "entries scanned");
   1014 	evcnt_attach_dynamic(&cache_ev_gc, EVCNT_TYPE_MISC, NULL,
   1015 	   "namecache", "entries collected");
   1016 	evcnt_attach_dynamic(&cache_ev_over, EVCNT_TYPE_MISC, NULL,
   1017 	   "namecache", "over scan target");
   1018 	evcnt_attach_dynamic(&cache_ev_under, EVCNT_TYPE_MISC, NULL,
   1019 	   "namecache", "under scan target");
   1020 	evcnt_attach_dynamic(&cache_ev_forced, EVCNT_TYPE_MISC, NULL,
   1021 	   "namecache", "forced reclaims");
   1022 
   1023 	sysctl_cache_stat_setup();
   1024 }
   1025 
   1026 static int
   1027 cache_ctor(void *arg, void *obj, int flag)
   1028 {
   1029 
   1030 	return 0;
   1031 }
   1032 
   1033 static void
   1034 cache_dtor(void *arg, void *obj)
   1035 {
   1036 
   1037 }
   1038 
   1039 /*
   1040  * Called once for each CPU in the system as attached.
   1041  */
   1042 void
   1043 cache_cpu_init(struct cpu_info *ci)
   1044 {
   1045 	struct nchcpu *cpup;
   1046 	size_t sz;
   1047 
   1048 	sz = roundup2(sizeof(*cpup), coherency_unit) + coherency_unit;
   1049 	cpup = kmem_zalloc(sz, KM_SLEEP);
   1050 	cpup = (void *)roundup2((uintptr_t)cpup, coherency_unit);
   1051 	mutex_init(&cpup->cpu_lock, MUTEX_DEFAULT, IPL_NONE);
   1052 	ci->ci_data.cpu_nch = cpup;
   1053 }
   1054 
   1055 /*
   1056  * Name cache reinitialization, for when the maximum number of vnodes increases.
   1057  */
   1058 void
   1059 nchreinit(void)
   1060 {
   1061 	struct namecache *ncp;
   1062 	struct nchashhead *oldhash1, *hash1;
   1063 	struct ncvhashhead *oldhash2, *hash2;
   1064 	u_long i, oldmask1, oldmask2, mask1, mask2;
   1065 
   1066 	hash1 = hashinit(desiredvnodes, HASH_LIST, true, &mask1);
   1067 	hash2 =
   1068 #ifdef NAMECACHE_ENTER_REVERSE
   1069 	    hashinit(desiredvnodes, HASH_LIST, true, &mask2);
   1070 #else
   1071 	    hashinit(desiredvnodes/8, HASH_LIST, true, &mask2);
   1072 #endif
   1073 	mutex_enter(&namecache_lock);
   1074 	cache_lock_cpus();
   1075 	oldhash1 = nchashtbl;
   1076 	oldmask1 = nchash;
   1077 	nchashtbl = hash1;
   1078 	nchash = mask1;
   1079 	oldhash2 = ncvhashtbl;
   1080 	oldmask2 = ncvhash;
   1081 	ncvhashtbl = hash2;
   1082 	ncvhash = mask2;
   1083 	for (i = 0; i <= oldmask1; i++) {
   1084 		while ((ncp = LIST_FIRST(&oldhash1[i])) != NULL) {
   1085 			LIST_REMOVE(ncp, nc_hash);
   1086 			ncp->nc_hash.le_prev = NULL;
   1087 		}
   1088 	}
   1089 	for (i = 0; i <= oldmask2; i++) {
   1090 		while ((ncp = LIST_FIRST(&oldhash2[i])) != NULL) {
   1091 			LIST_REMOVE(ncp, nc_vhash);
   1092 			ncp->nc_vhash.le_prev = NULL;
   1093 		}
   1094 	}
   1095 	cache_unlock_cpus();
   1096 	mutex_exit(&namecache_lock);
   1097 	hashdone(oldhash1, HASH_LIST, oldmask1);
   1098 	hashdone(oldhash2, HASH_LIST, oldmask2);
   1099 }
   1100 
   1101 /*
   1102  * Cache flush, a particular vnode; called when a vnode is renamed to
   1103  * hide entries that would now be invalid
   1104  */
   1105 void
   1106 cache_purge1(struct vnode *vp, const char *name, size_t namelen, int flags)
   1107 {
   1108 	struct namecache *ncp, *ncnext;
   1109 
   1110 	mutex_enter(&namecache_lock);
   1111 	if (flags & PURGE_PARENTS) {
   1112 		SDT_PROBE(vfs, namecache, purge, parents, vp, 0, 0, 0, 0);
   1113 
   1114 		for (ncp = LIST_FIRST(&VNODE_TO_VIMPL(vp)->vi_nclist);
   1115 		    ncp != NULL; ncp = ncnext) {
   1116 			ncnext = LIST_NEXT(ncp, nc_vlist);
   1117 			mutex_enter(ncp->nc_lock);
   1118 			cache_invalidate(ncp);
   1119 			mutex_exit(ncp->nc_lock);
   1120 			cache_disassociate(ncp);
   1121 		}
   1122 	}
   1123 	if (flags & PURGE_CHILDREN) {
   1124 		SDT_PROBE(vfs, namecache, purge, children, vp, 0, 0, 0, 0);
   1125 		for (ncp = LIST_FIRST(&VNODE_TO_VIMPL(vp)->vi_dnclist);
   1126 		    ncp != NULL; ncp = ncnext) {
   1127 			ncnext = LIST_NEXT(ncp, nc_dvlist);
   1128 			mutex_enter(ncp->nc_lock);
   1129 			cache_invalidate(ncp);
   1130 			mutex_exit(ncp->nc_lock);
   1131 			cache_disassociate(ncp);
   1132 		}
   1133 	}
   1134 	if (name != NULL) {
   1135 		SDT_PROBE(vfs, namecache, purge, name, name, namelen, 0, 0, 0);
   1136 		ncp = cache_lookup_entry(vp, name, namelen);
   1137 		if (ncp) {
   1138 			cache_invalidate(ncp);
   1139 			mutex_exit(ncp->nc_lock);
   1140 			cache_disassociate(ncp);
   1141 		}
   1142 	}
   1143 	mutex_exit(&namecache_lock);
   1144 }
   1145 
   1146 /*
   1147  * Cache flush, a whole filesystem; called when filesys is umounted to
   1148  * remove entries that would now be invalid.
   1149  */
   1150 void
   1151 cache_purgevfs(struct mount *mp)
   1152 {
   1153 	struct namecache *ncp, *nxtcp;
   1154 
   1155 	SDT_PROBE(vfs, namecache, purge, vfs, mp, 0, 0, 0, 0);
   1156 	mutex_enter(&namecache_lock);
   1157 	for (ncp = TAILQ_FIRST(&nclruhead); ncp != NULL; ncp = nxtcp) {
   1158 		nxtcp = TAILQ_NEXT(ncp, nc_lru);
   1159 		mutex_enter(ncp->nc_lock);
   1160 		if (ncp->nc_dvp != NULL && ncp->nc_dvp->v_mount == mp) {
   1161 			/* Free the resources we had. */
   1162 			cache_invalidate(ncp);
   1163 			cache_disassociate(ncp);
   1164 		}
   1165 		mutex_exit(ncp->nc_lock);
   1166 	}
   1167 	cache_reclaim();
   1168 	mutex_exit(&namecache_lock);
   1169 }
   1170 
   1171 /*
   1172  * Scan global list invalidating entries until we meet a preset target.
   1173  * Prefer to invalidate entries that have not scored a hit within
   1174  * cache_hottime seconds.  We sort the LRU list only for this routine's
   1175  * benefit.
   1176  */
   1177 static void
   1178 cache_prune(int incache, int target)
   1179 {
   1180 	struct namecache *ncp, *nxtcp, *sentinel;
   1181 	int items, recent, tryharder;
   1182 
   1183 	KASSERT(mutex_owned(&namecache_lock));
   1184 
   1185 	SDT_PROBE(vfs, namecache, prune, done, incache, target, 0, 0, 0);
   1186 	items = 0;
   1187 	tryharder = 0;
   1188 	recent = hardclock_ticks - hz * cache_hottime;
   1189 	sentinel = NULL;
   1190 	for (ncp = TAILQ_FIRST(&nclruhead); ncp != NULL; ncp = nxtcp) {
   1191 		if (incache <= target)
   1192 			break;
   1193 		items++;
   1194 		nxtcp = TAILQ_NEXT(ncp, nc_lru);
   1195 		if (ncp == sentinel) {
   1196 			/*
   1197 			 * If we looped back on ourself, then ignore
   1198 			 * recent entries and purge whatever we find.
   1199 			 */
   1200 			tryharder = 1;
   1201 		}
   1202 		if (ncp->nc_dvp == NULL)
   1203 			continue;
   1204 		if (!tryharder && (ncp->nc_hittime - recent) > 0) {
   1205 			if (sentinel == NULL)
   1206 				sentinel = ncp;
   1207 			TAILQ_REMOVE(&nclruhead, ncp, nc_lru);
   1208 			TAILQ_INSERT_TAIL(&nclruhead, ncp, nc_lru);
   1209 			continue;
   1210 		}
   1211 		mutex_enter(ncp->nc_lock);
   1212 		if (ncp->nc_dvp != NULL) {
   1213 			cache_invalidate(ncp);
   1214 			cache_disassociate(ncp);
   1215 			incache--;
   1216 		}
   1217 		mutex_exit(ncp->nc_lock);
   1218 	}
   1219 	cache_ev_scan.ev_count += items;
   1220 }
   1221 
   1222 /*
   1223  * Collect dead cache entries from all CPUs and garbage collect.
   1224  */
   1225 static void
   1226 cache_reclaim(void)
   1227 {
   1228 	CPU_INFO_ITERATOR cii;
   1229 	struct cpu_info *ci;
   1230 	struct nchcpu *cpup;
   1231 	struct namecache_gc_queue queue;
   1232 	struct namecache *ncp, *next;
   1233 	int items;
   1234 
   1235 	KASSERT(mutex_owned(&namecache_lock));
   1236 
   1237 	/*
   1238 	 * If the number of extant entries not awaiting garbage collection
   1239 	 * exceeds the high water mark, then reclaim stale entries until we
   1240 	 * reach our low water mark.
   1241 	 */
   1242 	items = numcache - namecache_gc_pend;
   1243 	if (items > (uint64_t)desiredvnodes * cache_hiwat / 100) {
   1244 		cache_prune(items, (int)((uint64_t)desiredvnodes *
   1245 		    cache_lowat / 100));
   1246 		cache_ev_over.ev_count++;
   1247 	} else
   1248 		cache_ev_under.ev_count++;
   1249 
   1250 	/* Chop the existing garbage collection list out. */
   1251 	mutex_enter(&namecache_gc_lock);
   1252 	queue = namecache_gc_queue;
   1253 	items = namecache_gc_pend;
   1254 	SLIST_INIT(&namecache_gc_queue);
   1255 	namecache_gc_pend = 0;
   1256 	mutex_exit(&namecache_gc_lock);
   1257 
   1258 	/*
   1259 	 * Now disassociate all entries.  We haven't locked out the reader
   1260 	 * side (cache_lookup_entry()) but the "next" pointers in the hash
   1261 	 * list will remain sufficiently consitent regardless of which
   1262 	 * version of the list the reader sees (see defs of LIST_FOREACH,
   1263 	 * LIST_NEXT);
   1264 	 */
   1265 	SLIST_FOREACH(ncp, &queue, nc_gclist) {
   1266 		cache_disassociate(ncp);
   1267 		KASSERT(ncp->nc_dvp == NULL);
   1268 		if (ncp->nc_hash.le_prev != NULL) {
   1269 			LIST_REMOVE(ncp, nc_hash);
   1270 			ncp->nc_hash.le_prev = NULL;
   1271 		}
   1272 	}
   1273 
   1274 	/*
   1275 	 * With that done, make sure our updates are visible on the bus, and
   1276 	 * make a pass to observe the status of all of the CPU locks.  If we
   1277 	 * see a lock is unheld, we know the garbage collected entries can
   1278 	 * no longer visible to that CPU.  If we see a lock IS held, we need
   1279 	 * to acquire and release it once to make sure that CPU is out of
   1280 	 * cache_lookup_entry().  Take the opportunity to refresh stats.
   1281 	 */
   1282 	membar_sync();	/* stores above vs. reads below */
   1283 	for (CPU_INFO_FOREACH(cii, ci)) {
   1284 		cpup = ci->ci_data.cpu_nch;
   1285 		if (__predict_false(mutex_owner(&cpup->cpu_lock) != NULL)) {
   1286 			mutex_enter(&cpup->cpu_lock);
   1287 			/* nothing */
   1288 			mutex_exit(&cpup->cpu_lock);
   1289 		}
   1290 		UPDATE(cpup, ncs_goodhits);
   1291 		UPDATE(cpup, ncs_neghits);
   1292 		UPDATE(cpup, ncs_badhits);
   1293 		UPDATE(cpup, ncs_falsehits);
   1294 		UPDATE(cpup, ncs_miss);
   1295 		UPDATE(cpup, ncs_long);
   1296 		UPDATE(cpup, ncs_pass2);
   1297 		UPDATE(cpup, ncs_2passes);
   1298 		UPDATE(cpup, ncs_revhits);
   1299 		UPDATE(cpup, ncs_revmiss);
   1300 	}
   1301 	membar_sync();	/* reads above vs. stores below */
   1302 
   1303 	/*
   1304 	 * Nobody else can see the cache entries any more.  Make a final
   1305 	 * pass over the list and toss the contents.
   1306 	 */
   1307 	SLIST_FOREACH_SAFE(ncp, &queue, nc_gclist, next) {
   1308 		mutex_obj_free(ncp->nc_lock);
   1309 		ncp->nc_lock = NULL;
   1310 		if (ncp->nc_nlen > NCHNAMLEN) {
   1311 			cache_dtor(NULL, ncp);
   1312 			kmem_free(ncp, sizeof(*ncp) + ncp->nc_nlen);
   1313 		} else
   1314 			pool_cache_put(namecache_cache, ncp);
   1315 	}
   1316 
   1317 	numcache -= items;
   1318 	cache_ev_gc.ev_count += items;
   1319 }
   1320 
   1321 /*
   1322  * Cache maintainence thread, awakening once per second to:
   1323  *
   1324  * => keep number of entries below the high water mark
   1325  * => sort pseudo-LRU list
   1326  * => garbage collect dead entries
   1327  */
   1328 static void
   1329 cache_thread(void *arg)
   1330 {
   1331 
   1332 	mutex_enter(&namecache_lock);
   1333 	for (;;) {
   1334 		cache_reclaim();
   1335 		kpause("cachegc", false, hz, &namecache_lock);
   1336 	}
   1337 }
   1338 
   1339 #ifdef DDB
   1340 void
   1341 namecache_print(struct vnode *vp, void (*pr)(const char *, ...))
   1342 {
   1343 	struct vnode *dvp = NULL;
   1344 	struct namecache *ncp;
   1345 
   1346 	TAILQ_FOREACH(ncp, &nclruhead, nc_lru) {
   1347 		if (ncp->nc_vp == vp && ncp->nc_dvp != NULL) {
   1348 			(*pr)("name %.*s\n", ncp->nc_nlen, ncp->nc_name);
   1349 			dvp = ncp->nc_dvp;
   1350 		}
   1351 	}
   1352 	if (dvp == NULL) {
   1353 		(*pr)("name not found\n");
   1354 		return;
   1355 	}
   1356 	vp = dvp;
   1357 	TAILQ_FOREACH(ncp, &nclruhead, nc_lru) {
   1358 		if (ncp->nc_vp == vp) {
   1359 			(*pr)("parent %.*s\n", ncp->nc_nlen, ncp->nc_name);
   1360 		}
   1361 	}
   1362 }
   1363 #endif
   1364 
   1365 void
   1366 namecache_count_pass2(void)
   1367 {
   1368 	struct nchcpu *cpup = curcpu()->ci_data.cpu_nch;
   1369 
   1370 	COUNT_UNL(cpup, ncs_pass2);
   1371 }
   1372 
   1373 void
   1374 namecache_count_2passes(void)
   1375 {
   1376 	struct nchcpu *cpup = curcpu()->ci_data.cpu_nch;
   1377 
   1378 	COUNT_UNL(cpup, ncs_2passes);
   1379 }
   1380 
   1381 /*
   1382  * Fetch the current values of the stats.  We return the most
   1383  * recent values harvested into nchstats by cache_reclaim(), which
   1384  * will be less than a second old.
   1385  */
   1386 static int
   1387 cache_stat_sysctl(SYSCTLFN_ARGS)
   1388 {
   1389 	CPU_INFO_ITERATOR cii;
   1390 	struct cpu_info *ci;
   1391 
   1392 	if (oldp == NULL) {
   1393 		*oldlenp = sizeof(nchstats);
   1394 		return 0;
   1395 	}
   1396 
   1397 	if (*oldlenp < sizeof(nchstats)) {
   1398 		*oldlenp = 0;
   1399 		return 0;
   1400 	}
   1401 
   1402 	sysctl_unlock();
   1403 	mutex_enter(&namecache_lock);
   1404 	for (CPU_INFO_FOREACH(cii, ci)) {
   1405 		struct nchcpu *cpup = ci->ci_data.cpu_nch;
   1406 
   1407 		UPDATE(cpup, ncs_goodhits);
   1408 		UPDATE(cpup, ncs_neghits);
   1409 		UPDATE(cpup, ncs_badhits);
   1410 		UPDATE(cpup, ncs_falsehits);
   1411 		UPDATE(cpup, ncs_miss);
   1412 
   1413 		UPDATE(cpup, ncs_pass2);
   1414 		UPDATE(cpup, ncs_2passes);
   1415 		UPDATE(cpup, ncs_revhits);
   1416 		UPDATE(cpup, ncs_revmiss);
   1417 	}
   1418 	mutex_exit(&namecache_lock);
   1419 	sysctl_relock();
   1420 
   1421 	*oldlenp = sizeof(nchstats);
   1422 	return sysctl_copyout(l, &nchstats, oldp, sizeof(nchstats));
   1423 }
   1424 
   1425 static void
   1426 sysctl_cache_stat_setup(void)
   1427 {
   1428 
   1429 	KASSERT(sysctllog == NULL);
   1430 	sysctl_createv(&sysctllog, 0, NULL, NULL,
   1431 		       CTLFLAG_PERMANENT,
   1432 		       CTLTYPE_STRUCT, "namecache_stats",
   1433 		       SYSCTL_DESCR("namecache statistics"),
   1434 		       cache_stat_sysctl, 0, NULL, 0,
   1435 		       CTL_VFS, CTL_CREATE, CTL_EOL);
   1436 }
   1437