Home | History | Annotate | Line # | Download | only in kern
vfs_cache.c revision 1.97
      1 /*	$NetBSD: vfs_cache.c,v 1.97 2014/06/03 21:16:15 joerg Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2008 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.97 2014/06/03 21:16:15 joerg Exp $");
     62 
     63 #include "opt_ddb.h"
     64 #include "opt_revcache.h"
     65 
     66 #include <sys/param.h>
     67 #include <sys/systm.h>
     68 #include <sys/sysctl.h>
     69 #include <sys/time.h>
     70 #include <sys/mount.h>
     71 #include <sys/vnode.h>
     72 #include <sys/namei.h>
     73 #include <sys/errno.h>
     74 #include <sys/pool.h>
     75 #include <sys/mutex.h>
     76 #include <sys/atomic.h>
     77 #include <sys/kthread.h>
     78 #include <sys/kernel.h>
     79 #include <sys/cpu.h>
     80 #include <sys/evcnt.h>
     81 
     82 #define NAMECACHE_ENTER_REVERSE
     83 /*
     84  * Name caching works as follows:
     85  *
     86  * Names found by directory scans are retained in a cache
     87  * for future reference.  It is managed LRU, so frequently
     88  * used names will hang around.  Cache is indexed by hash value
     89  * obtained from (dvp, name) where dvp refers to the directory
     90  * containing name.
     91  *
     92  * For simplicity (and economy of storage), names longer than
     93  * a maximum length of NCHNAMLEN are not cached; they occur
     94  * infrequently in any case, and are almost never of interest.
     95  *
     96  * Upon reaching the last segment of a path, if the reference
     97  * is for DELETE, or NOCACHE is set (rewrite), and the
     98  * name is located in the cache, it will be dropped.
     99  * The entry is dropped also when it was not possible to lock
    100  * the cached vnode, either because vget() failed or the generation
    101  * number has changed while waiting for the lock.
    102  */
    103 
    104 /*
    105  * Per-cpu namecache data.
    106  */
    107 struct nchcpu {
    108 	kmutex_t	cpu_lock;
    109 	struct nchstats	cpu_stats;
    110 };
    111 
    112 /*
    113  * The type for the hash code. While the hash function generates a
    114  * u32, the hash code has historically been passed around as a u_long,
    115  * and the value is modified by xor'ing a uintptr_t, so it's not
    116  * entirely clear what the best type is. For now I'll leave it
    117  * unchanged as u_long.
    118  */
    119 
    120 typedef u_long nchash_t;
    121 
    122 /*
    123  * Structures associated with name cacheing.
    124  */
    125 
    126 static kmutex_t *namecache_lock __read_mostly;
    127 static pool_cache_t namecache_cache __read_mostly;
    128 static TAILQ_HEAD(, namecache) nclruhead __cacheline_aligned;
    129 
    130 static LIST_HEAD(nchashhead, namecache) *nchashtbl __read_mostly;
    131 static u_long	nchash __read_mostly;
    132 
    133 #define	NCHASH2(hash, dvp)	\
    134 	(((hash) ^ ((uintptr_t)(dvp) >> 3)) & nchash)
    135 
    136 static LIST_HEAD(ncvhashhead, namecache) *ncvhashtbl __read_mostly;
    137 static u_long	ncvhash __read_mostly;
    138 
    139 #define	NCVHASH(vp)		(((uintptr_t)(vp) >> 3) & ncvhash)
    140 
    141 /* Number of cache entries allocated. */
    142 static long	numcache __cacheline_aligned;
    143 
    144 /* Garbage collection queue and number of entries pending in it. */
    145 static void	*cache_gcqueue;
    146 static u_int	cache_gcpend;
    147 
    148 /* Cache effectiveness statistics. */
    149 struct nchstats	nchstats __cacheline_aligned;
    150 #define	COUNT(c,x)	(c.x++)
    151 
    152 static const int cache_lowat = 95;
    153 static const int cache_hiwat = 98;
    154 static const int cache_hottime = 5;	/* number of seconds */
    155 static int doingcache = 1;		/* 1 => enable the cache */
    156 
    157 static struct evcnt cache_ev_scan;
    158 static struct evcnt cache_ev_gc;
    159 static struct evcnt cache_ev_over;
    160 static struct evcnt cache_ev_under;
    161 static struct evcnt cache_ev_forced;
    162 
    163 static void cache_invalidate(struct namecache *);
    164 static struct namecache *cache_lookup_entry(
    165     const struct vnode *, const char *, size_t);
    166 static void cache_thread(void *);
    167 static void cache_invalidate(struct namecache *);
    168 static void cache_disassociate(struct namecache *);
    169 static void cache_reclaim(void);
    170 static int cache_ctor(void *, void *, int);
    171 static void cache_dtor(void *, void *);
    172 
    173 /*
    174  * Compute the hash for an entry.
    175  *
    176  * (This is for now a wrapper around namei_hash, whose interface is
    177  * for the time being slightly inconvenient.)
    178  */
    179 static nchash_t
    180 cache_hash(const char *name, size_t namelen)
    181 {
    182 	const char *endptr;
    183 
    184 	endptr = name + namelen;
    185 	return namei_hash(name, &endptr);
    186 }
    187 
    188 /*
    189  * Invalidate a cache entry and enqueue it for garbage collection.
    190  */
    191 static void
    192 cache_invalidate(struct namecache *ncp)
    193 {
    194 	void *head;
    195 
    196 	KASSERT(mutex_owned(&ncp->nc_lock));
    197 
    198 	if (ncp->nc_dvp != NULL) {
    199 		ncp->nc_vp = NULL;
    200 		ncp->nc_dvp = NULL;
    201 		do {
    202 			head = cache_gcqueue;
    203 			ncp->nc_gcqueue = head;
    204 		} while (atomic_cas_ptr(&cache_gcqueue, head, ncp) != head);
    205 		atomic_inc_uint(&cache_gcpend);
    206 	}
    207 }
    208 
    209 /*
    210  * Disassociate a namecache entry from any vnodes it is attached to,
    211  * and remove from the global LRU list.
    212  */
    213 static void
    214 cache_disassociate(struct namecache *ncp)
    215 {
    216 
    217 	KASSERT(mutex_owned(namecache_lock));
    218 	KASSERT(ncp->nc_dvp == NULL);
    219 
    220 	if (ncp->nc_lru.tqe_prev != NULL) {
    221 		TAILQ_REMOVE(&nclruhead, ncp, nc_lru);
    222 		ncp->nc_lru.tqe_prev = NULL;
    223 	}
    224 	if (ncp->nc_vhash.le_prev != NULL) {
    225 		LIST_REMOVE(ncp, nc_vhash);
    226 		ncp->nc_vhash.le_prev = NULL;
    227 	}
    228 	if (ncp->nc_vlist.le_prev != NULL) {
    229 		LIST_REMOVE(ncp, nc_vlist);
    230 		ncp->nc_vlist.le_prev = NULL;
    231 	}
    232 	if (ncp->nc_dvlist.le_prev != NULL) {
    233 		LIST_REMOVE(ncp, nc_dvlist);
    234 		ncp->nc_dvlist.le_prev = NULL;
    235 	}
    236 }
    237 
    238 /*
    239  * Lock all CPUs to prevent any cache lookup activity.  Conceptually,
    240  * this locks out all "readers".
    241  */
    242 #define	UPDATE(f) do { \
    243 	nchstats.f += cpup->cpu_stats.f; \
    244 	cpup->cpu_stats.f = 0; \
    245 } while (/* CONSTCOND */ 0)
    246 
    247 static void
    248 cache_lock_cpus(void)
    249 {
    250 	CPU_INFO_ITERATOR cii;
    251 	struct cpu_info *ci;
    252 	struct nchcpu *cpup;
    253 
    254 	for (CPU_INFO_FOREACH(cii, ci)) {
    255 		cpup = ci->ci_data.cpu_nch;
    256 		mutex_enter(&cpup->cpu_lock);
    257 		UPDATE(ncs_goodhits);
    258 		UPDATE(ncs_neghits);
    259 		UPDATE(ncs_badhits);
    260 		UPDATE(ncs_falsehits);
    261 		UPDATE(ncs_miss);
    262 		UPDATE(ncs_long);
    263 		UPDATE(ncs_pass2);
    264 		UPDATE(ncs_2passes);
    265 		UPDATE(ncs_revhits);
    266 		UPDATE(ncs_revmiss);
    267 	}
    268 }
    269 
    270 #undef UPDATE
    271 
    272 /*
    273  * Release all CPU locks.
    274  */
    275 static void
    276 cache_unlock_cpus(void)
    277 {
    278 	CPU_INFO_ITERATOR cii;
    279 	struct cpu_info *ci;
    280 	struct nchcpu *cpup;
    281 
    282 	for (CPU_INFO_FOREACH(cii, ci)) {
    283 		cpup = ci->ci_data.cpu_nch;
    284 		mutex_exit(&cpup->cpu_lock);
    285 	}
    286 }
    287 
    288 /*
    289  * Find a single cache entry and return it locked.  'namecache_lock' or
    290  * at least one of the per-CPU locks must be held.
    291  */
    292 static struct namecache *
    293 cache_lookup_entry(const struct vnode *dvp, const char *name, size_t namelen)
    294 {
    295 	struct nchashhead *ncpp;
    296 	struct namecache *ncp;
    297 	nchash_t hash;
    298 
    299 	KASSERT(dvp != NULL);
    300 	hash = cache_hash(name, namelen);
    301 	ncpp = &nchashtbl[NCHASH2(hash, dvp)];
    302 
    303 	LIST_FOREACH(ncp, ncpp, nc_hash) {
    304 		if (ncp->nc_dvp != dvp ||
    305 		    ncp->nc_nlen != namelen ||
    306 		    memcmp(ncp->nc_name, name, (u_int)ncp->nc_nlen))
    307 		    	continue;
    308 	    	mutex_enter(&ncp->nc_lock);
    309 		if (__predict_true(ncp->nc_dvp == dvp)) {
    310 			ncp->nc_hittime = hardclock_ticks;
    311 			return ncp;
    312 		}
    313 		/* Raced: entry has been nullified. */
    314 		mutex_exit(&ncp->nc_lock);
    315 	}
    316 
    317 	return NULL;
    318 }
    319 
    320 /*
    321  * Look for a the name in the cache. We don't do this
    322  * if the segment name is long, simply so the cache can avoid
    323  * holding long names (which would either waste space, or
    324  * add greatly to the complexity).
    325  *
    326  * Lookup is called with DVP pointing to the directory to search,
    327  * and CNP providing the name of the entry being sought: cn_nameptr
    328  * is the name, cn_namelen is its length, and cn_flags is the flags
    329  * word from the namei operation.
    330  *
    331  * DVP must be locked.
    332  *
    333  * There are three possible non-error return states:
    334  *    1. Nothing was found in the cache. Nothing is known about
    335  *       the requested name.
    336  *    2. A negative entry was found in the cache, meaning that the
    337  *       requested name definitely does not exist.
    338  *    3. A positive entry was found in the cache, meaning that the
    339  *       requested name does exist and that we are providing the
    340  *       vnode.
    341  * In these cases the results are:
    342  *    1. 0 returned; VN is set to NULL.
    343  *    2. 1 returned; VN is set to NULL.
    344  *    3. 1 returned; VN is set to the vnode found.
    345  *
    346  * The additional result argument ISWHT is set to zero, unless a
    347  * negative entry is found that was entered as a whiteout, in which
    348  * case ISWHT is set to one.
    349  *
    350  * The ISWHT_RET argument pointer may be null. In this case an
    351  * assertion is made that the whiteout flag is not set. File systems
    352  * that do not support whiteouts can/should do this.
    353  *
    354  * Filesystems that do support whiteouts should add ISWHITEOUT to
    355  * cnp->cn_flags if ISWHT comes back nonzero.
    356  *
    357  * When a vnode is returned, it is locked, as per the vnode lookup
    358  * locking protocol.
    359  *
    360  * There is no way for this function to fail, in the sense of
    361  * generating an error that requires aborting the namei operation.
    362  *
    363  * (Prior to October 2012, this function returned an integer status,
    364  * and a vnode, and mucked with the flags word in CNP for whiteouts.
    365  * The integer status was -1 for "nothing found", ENOENT for "a
    366  * negative entry found", 0 for "a positive entry found", and possibly
    367  * other errors, and the value of VN might or might not have been set
    368  * depending on what error occurred.)
    369  */
    370 int
    371 cache_lookup(struct vnode *dvp, const char *name, size_t namelen,
    372 	     uint32_t nameiop, uint32_t cnflags,
    373 	     int *iswht_ret, struct vnode **vn_ret)
    374 {
    375 	struct namecache *ncp;
    376 	struct vnode *vp;
    377 	struct nchcpu *cpup;
    378 	int error;
    379 
    380 	/* Establish default result values */
    381 	if (iswht_ret != NULL) {
    382 		*iswht_ret = 0;
    383 	}
    384 	*vn_ret = NULL;
    385 
    386 	if (__predict_false(!doingcache)) {
    387 		return 0;
    388 	}
    389 
    390 	cpup = curcpu()->ci_data.cpu_nch;
    391 	mutex_enter(&cpup->cpu_lock);
    392 	if (__predict_false(namelen > NCHNAMLEN)) {
    393 		COUNT(cpup->cpu_stats, ncs_long);
    394 		mutex_exit(&cpup->cpu_lock);
    395 		/* found nothing */
    396 		return 0;
    397 	}
    398 	ncp = cache_lookup_entry(dvp, name, namelen);
    399 	if (__predict_false(ncp == NULL)) {
    400 		COUNT(cpup->cpu_stats, ncs_miss);
    401 		mutex_exit(&cpup->cpu_lock);
    402 		/* found nothing */
    403 		return 0;
    404 	}
    405 	if ((cnflags & MAKEENTRY) == 0) {
    406 		COUNT(cpup->cpu_stats, ncs_badhits);
    407 		/*
    408 		 * Last component and we are renaming or deleting,
    409 		 * the cache entry is invalid, or otherwise don't
    410 		 * want cache entry to exist.
    411 		 */
    412 		cache_invalidate(ncp);
    413 		mutex_exit(&ncp->nc_lock);
    414 		mutex_exit(&cpup->cpu_lock);
    415 		/* found nothing */
    416 		return 0;
    417 	}
    418 	if (ncp->nc_vp == NULL) {
    419 		if (iswht_ret != NULL) {
    420 			/*
    421 			 * Restore the ISWHITEOUT flag saved earlier.
    422 			 */
    423 			KASSERT((ncp->nc_flags & ~ISWHITEOUT) == 0);
    424 			*iswht_ret = (ncp->nc_flags & ISWHITEOUT) != 0;
    425 		} else {
    426 			KASSERT(ncp->nc_flags == 0);
    427 		}
    428 
    429 		if (__predict_true(nameiop != CREATE ||
    430 		    (cnflags & ISLASTCN) == 0)) {
    431 			COUNT(cpup->cpu_stats, ncs_neghits);
    432 			mutex_exit(&ncp->nc_lock);
    433 			mutex_exit(&cpup->cpu_lock);
    434 			/* found neg entry; vn is already null from above */
    435 			return 1;
    436 		} else {
    437 			COUNT(cpup->cpu_stats, ncs_badhits);
    438 			/*
    439 			 * Last component and we are renaming or
    440 			 * deleting, the cache entry is invalid,
    441 			 * or otherwise don't want cache entry to
    442 			 * exist.
    443 			 */
    444 			cache_invalidate(ncp);
    445 			mutex_exit(&ncp->nc_lock);
    446 			mutex_exit(&cpup->cpu_lock);
    447 			/* found nothing */
    448 			return 0;
    449 		}
    450 	}
    451 
    452 	vp = ncp->nc_vp;
    453 	mutex_enter(vp->v_interlock);
    454 	mutex_exit(&ncp->nc_lock);
    455 	mutex_exit(&cpup->cpu_lock);
    456 	error = vget(vp, LK_NOWAIT);
    457 	if (error) {
    458 		KASSERT(error == EBUSY);
    459 		/*
    460 		 * This vnode is being cleaned out.
    461 		 * XXX badhits?
    462 		 */
    463 		COUNT(cpup->cpu_stats, ncs_falsehits);
    464 		/* found nothing */
    465 		return 0;
    466 	}
    467 
    468 #ifdef DEBUG
    469 	/*
    470 	 * since we released nb->nb_lock,
    471 	 * we can't use this pointer any more.
    472 	 */
    473 	ncp = NULL;
    474 #endif /* DEBUG */
    475 
    476 	/* We don't have the right lock, but this is only for stats. */
    477 	COUNT(cpup->cpu_stats, ncs_goodhits);
    478 
    479 	/* found it */
    480 	*vn_ret = vp;
    481 	return 1;
    482 }
    483 
    484 int
    485 cache_lookup_raw(struct vnode *dvp, const char *name, size_t namelen,
    486 		 uint32_t cnflags,
    487 		 int *iswht_ret, struct vnode **vn_ret)
    488 {
    489 	struct namecache *ncp;
    490 	struct vnode *vp;
    491 	struct nchcpu *cpup;
    492 	int error;
    493 
    494 	/* Establish default results. */
    495 	if (iswht_ret != NULL) {
    496 		*iswht_ret = 0;
    497 	}
    498 	*vn_ret = NULL;
    499 
    500 	if (__predict_false(!doingcache)) {
    501 		/* found nothing */
    502 		return 0;
    503 	}
    504 
    505 	cpup = curcpu()->ci_data.cpu_nch;
    506 	mutex_enter(&cpup->cpu_lock);
    507 	if (__predict_false(namelen > NCHNAMLEN)) {
    508 		COUNT(cpup->cpu_stats, ncs_long);
    509 		mutex_exit(&cpup->cpu_lock);
    510 		/* found nothing */
    511 		return 0;
    512 	}
    513 	ncp = cache_lookup_entry(dvp, name, namelen);
    514 	if (__predict_false(ncp == NULL)) {
    515 		COUNT(cpup->cpu_stats, ncs_miss);
    516 		mutex_exit(&cpup->cpu_lock);
    517 		/* found nothing */
    518 		return 0;
    519 	}
    520 	vp = ncp->nc_vp;
    521 	if (vp == NULL) {
    522 		/*
    523 		 * Restore the ISWHITEOUT flag saved earlier.
    524 		 */
    525 		if (iswht_ret != NULL) {
    526 			KASSERT((ncp->nc_flags & ~ISWHITEOUT) == 0);
    527 			/*cnp->cn_flags |= ncp->nc_flags;*/
    528 			*iswht_ret = (ncp->nc_flags & ISWHITEOUT) != 0;
    529 		}
    530 		COUNT(cpup->cpu_stats, ncs_neghits);
    531 		mutex_exit(&ncp->nc_lock);
    532 		mutex_exit(&cpup->cpu_lock);
    533 		/* found negative entry; vn is already null from above */
    534 		return 1;
    535 	}
    536 	mutex_enter(vp->v_interlock);
    537 	mutex_exit(&ncp->nc_lock);
    538 	mutex_exit(&cpup->cpu_lock);
    539 	error = vget(vp, LK_NOWAIT);
    540 	if (error) {
    541 		KASSERT(error == EBUSY);
    542 		/*
    543 		 * This vnode is being cleaned out.
    544 		 * XXX badhits?
    545 		 */
    546 		COUNT(cpup->cpu_stats, ncs_falsehits);
    547 		/* found nothing */
    548 		return 0;
    549 	}
    550 
    551 	/* Unlocked, but only for stats. */
    552 	COUNT(cpup->cpu_stats, ncs_goodhits); /* XXX can be "badhits" */
    553 
    554 	/* found it */
    555 	*vn_ret = vp;
    556 	return 1;
    557 }
    558 
    559 /*
    560  * Scan cache looking for name of directory entry pointing at vp.
    561  *
    562  * If the lookup succeeds the vnode is referenced and stored in dvpp.
    563  *
    564  * If bufp is non-NULL, also place the name in the buffer which starts
    565  * at bufp, immediately before *bpp, and move bpp backwards to point
    566  * at the start of it.  (Yes, this is a little baroque, but it's done
    567  * this way to cater to the whims of getcwd).
    568  *
    569  * Returns 0 on success, -1 on cache miss, positive errno on failure.
    570  */
    571 int
    572 cache_revlookup(struct vnode *vp, struct vnode **dvpp, char **bpp, char *bufp)
    573 {
    574 	struct namecache *ncp;
    575 	struct vnode *dvp;
    576 	struct nchcpu *cpup;
    577 	struct ncvhashhead *nvcpp;
    578 	char *bp;
    579 	int error, nlen;
    580 
    581 	if (!doingcache)
    582 		goto out;
    583 
    584 	nvcpp = &ncvhashtbl[NCVHASH(vp)];
    585 	cpup = curcpu()->ci_data.cpu_nch;
    586 
    587 	mutex_enter(namecache_lock);
    588 	LIST_FOREACH(ncp, nvcpp, nc_vhash) {
    589 		mutex_enter(&ncp->nc_lock);
    590 		if (ncp->nc_vp == vp &&
    591 		    (dvp = ncp->nc_dvp) != NULL &&
    592 		    dvp != vp) { 		/* avoid pesky . entries.. */
    593 
    594 #ifdef DIAGNOSTIC
    595 			if (ncp->nc_nlen == 1 &&
    596 			    ncp->nc_name[0] == '.')
    597 				panic("cache_revlookup: found entry for .");
    598 
    599 			if (ncp->nc_nlen == 2 &&
    600 			    ncp->nc_name[0] == '.' &&
    601 			    ncp->nc_name[1] == '.')
    602 				panic("cache_revlookup: found entry for ..");
    603 #endif
    604 			mutex_enter(&cpup->cpu_lock);
    605 			COUNT(cpup->cpu_stats, ncs_revhits);
    606 			mutex_exit(&cpup->cpu_lock);
    607 			nlen = ncp->nc_nlen;
    608 
    609 			if (bufp) {
    610 				bp = *bpp;
    611 				bp -= nlen;
    612 				if (bp <= bufp) {
    613 					*dvpp = NULL;
    614 					mutex_exit(&ncp->nc_lock);
    615 					mutex_exit(namecache_lock);
    616 					return (ERANGE);
    617 				}
    618 				memcpy(bp, ncp->nc_name, nlen);
    619 				*bpp = bp;
    620 			}
    621 
    622 			mutex_enter(dvp->v_interlock);
    623 			mutex_exit(&ncp->nc_lock);
    624 			mutex_exit(namecache_lock);
    625 			error = vget(dvp, LK_NOWAIT);
    626 			if (error) {
    627 				KASSERT(error == EBUSY);
    628 				if (bufp)
    629 					(*bpp) += nlen;
    630 				*dvpp = NULL;
    631 				return -1;
    632 			}
    633 			*dvpp = dvp;
    634 			return (0);
    635 		}
    636 		mutex_exit(&ncp->nc_lock);
    637 	}
    638 	mutex_enter(&cpup->cpu_lock);
    639 	COUNT(cpup->cpu_stats, ncs_revmiss);
    640 	mutex_exit(&cpup->cpu_lock);
    641 	mutex_exit(namecache_lock);
    642  out:
    643 	*dvpp = NULL;
    644 	return (-1);
    645 }
    646 
    647 /*
    648  * Add an entry to the cache
    649  */
    650 void
    651 cache_enter(struct vnode *dvp, struct vnode *vp,
    652 	    const char *name, size_t namelen, uint32_t cnflags)
    653 {
    654 	struct namecache *ncp;
    655 	struct namecache *oncp;
    656 	struct nchashhead *ncpp;
    657 	struct ncvhashhead *nvcpp;
    658 	nchash_t hash;
    659 
    660 	/* First, check whether we can/should add a cache entry. */
    661 	if ((cnflags & MAKEENTRY) == 0 ||
    662 	    __predict_false(namelen > NCHNAMLEN || !doingcache)) {
    663 		return;
    664 	}
    665 
    666 	if (numcache > desiredvnodes) {
    667 		mutex_enter(namecache_lock);
    668 		cache_ev_forced.ev_count++;
    669 		cache_reclaim();
    670 		mutex_exit(namecache_lock);
    671 	}
    672 
    673 	ncp = pool_cache_get(namecache_cache, PR_WAITOK);
    674 	mutex_enter(namecache_lock);
    675 	numcache++;
    676 
    677 	/*
    678 	 * Concurrent lookups in the same directory may race for a
    679 	 * cache entry.  if there's a duplicated entry, free it.
    680 	 */
    681 	oncp = cache_lookup_entry(dvp, name, namelen);
    682 	if (oncp) {
    683 		cache_invalidate(oncp);
    684 		mutex_exit(&oncp->nc_lock);
    685 	}
    686 
    687 	/* Grab the vnode we just found. */
    688 	mutex_enter(&ncp->nc_lock);
    689 	ncp->nc_vp = vp;
    690 	ncp->nc_flags = 0;
    691 	ncp->nc_hittime = 0;
    692 	ncp->nc_gcqueue = NULL;
    693 	if (vp == NULL) {
    694 		/*
    695 		 * For negative hits, save the ISWHITEOUT flag so we can
    696 		 * restore it later when the cache entry is used again.
    697 		 */
    698 		ncp->nc_flags = cnflags & ISWHITEOUT;
    699 	}
    700 
    701 	/* Fill in cache info. */
    702 	ncp->nc_dvp = dvp;
    703 	LIST_INSERT_HEAD(&dvp->v_dnclist, ncp, nc_dvlist);
    704 	if (vp)
    705 		LIST_INSERT_HEAD(&vp->v_nclist, ncp, nc_vlist);
    706 	else {
    707 		ncp->nc_vlist.le_prev = NULL;
    708 		ncp->nc_vlist.le_next = NULL;
    709 	}
    710 	KASSERT(namelen <= NCHNAMLEN);
    711 	ncp->nc_nlen = namelen;
    712 	memcpy(ncp->nc_name, name, (unsigned)ncp->nc_nlen);
    713 	TAILQ_INSERT_TAIL(&nclruhead, ncp, nc_lru);
    714 	hash = cache_hash(name, namelen);
    715 	ncpp = &nchashtbl[NCHASH2(hash, dvp)];
    716 
    717 	/*
    718 	 * Flush updates before making visible in table.  No need for a
    719 	 * memory barrier on the other side: to see modifications the
    720 	 * list must be followed, meaning a dependent pointer load.
    721 	 * The below is LIST_INSERT_HEAD() inlined, with the memory
    722 	 * barrier included in the correct place.
    723 	 */
    724 	if ((ncp->nc_hash.le_next = ncpp->lh_first) != NULL)
    725 		ncpp->lh_first->nc_hash.le_prev = &ncp->nc_hash.le_next;
    726 	ncp->nc_hash.le_prev = &ncpp->lh_first;
    727 	membar_producer();
    728 	ncpp->lh_first = ncp;
    729 
    730 	ncp->nc_vhash.le_prev = NULL;
    731 	ncp->nc_vhash.le_next = NULL;
    732 
    733 	/*
    734 	 * Create reverse-cache entries (used in getcwd) for directories.
    735 	 * (and in linux procfs exe node)
    736 	 */
    737 	if (vp != NULL &&
    738 	    vp != dvp &&
    739 #ifndef NAMECACHE_ENTER_REVERSE
    740 	    vp->v_type == VDIR &&
    741 #endif
    742 	    (ncp->nc_nlen > 2 ||
    743 	    (ncp->nc_nlen > 1 && ncp->nc_name[1] != '.') ||
    744 	    (/* ncp->nc_nlen > 0 && */ ncp->nc_name[0] != '.'))) {
    745 		nvcpp = &ncvhashtbl[NCVHASH(vp)];
    746 		LIST_INSERT_HEAD(nvcpp, ncp, nc_vhash);
    747 	}
    748 	mutex_exit(&ncp->nc_lock);
    749 	mutex_exit(namecache_lock);
    750 }
    751 
    752 /*
    753  * Name cache initialization, from vfs_init() when we are booting
    754  */
    755 void
    756 nchinit(void)
    757 {
    758 	int error;
    759 
    760 	TAILQ_INIT(&nclruhead);
    761 	namecache_cache = pool_cache_init(sizeof(struct namecache),
    762 	    coherency_unit, 0, 0, "ncache", NULL, IPL_NONE, cache_ctor,
    763 	    cache_dtor, NULL);
    764 	KASSERT(namecache_cache != NULL);
    765 
    766 	namecache_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE);
    767 
    768 	nchashtbl = hashinit(desiredvnodes, HASH_LIST, true, &nchash);
    769 	ncvhashtbl =
    770 #ifdef NAMECACHE_ENTER_REVERSE
    771 	    hashinit(desiredvnodes, HASH_LIST, true, &ncvhash);
    772 #else
    773 	    hashinit(desiredvnodes/8, HASH_LIST, true, &ncvhash);
    774 #endif
    775 
    776 	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, cache_thread,
    777 	    NULL, NULL, "cachegc");
    778 	if (error != 0)
    779 		panic("nchinit %d", error);
    780 
    781 	evcnt_attach_dynamic(&cache_ev_scan, EVCNT_TYPE_MISC, NULL,
    782 	   "namecache", "entries scanned");
    783 	evcnt_attach_dynamic(&cache_ev_gc, EVCNT_TYPE_MISC, NULL,
    784 	   "namecache", "entries collected");
    785 	evcnt_attach_dynamic(&cache_ev_over, EVCNT_TYPE_MISC, NULL,
    786 	   "namecache", "over scan target");
    787 	evcnt_attach_dynamic(&cache_ev_under, EVCNT_TYPE_MISC, NULL,
    788 	   "namecache", "under scan target");
    789 	evcnt_attach_dynamic(&cache_ev_forced, EVCNT_TYPE_MISC, NULL,
    790 	   "namecache", "forced reclaims");
    791 }
    792 
    793 static int
    794 cache_ctor(void *arg, void *obj, int flag)
    795 {
    796 	struct namecache *ncp;
    797 
    798 	ncp = obj;
    799 	mutex_init(&ncp->nc_lock, MUTEX_DEFAULT, IPL_NONE);
    800 
    801 	return 0;
    802 }
    803 
    804 static void
    805 cache_dtor(void *arg, void *obj)
    806 {
    807 	struct namecache *ncp;
    808 
    809 	ncp = obj;
    810 	mutex_destroy(&ncp->nc_lock);
    811 }
    812 
    813 /*
    814  * Called once for each CPU in the system as attached.
    815  */
    816 void
    817 cache_cpu_init(struct cpu_info *ci)
    818 {
    819 	struct nchcpu *cpup;
    820 	size_t sz;
    821 
    822 	sz = roundup2(sizeof(*cpup), coherency_unit) + coherency_unit;
    823 	cpup = kmem_zalloc(sz, KM_SLEEP);
    824 	cpup = (void *)roundup2((uintptr_t)cpup, coherency_unit);
    825 	mutex_init(&cpup->cpu_lock, MUTEX_DEFAULT, IPL_NONE);
    826 	ci->ci_data.cpu_nch = cpup;
    827 }
    828 
    829 /*
    830  * Name cache reinitialization, for when the maximum number of vnodes increases.
    831  */
    832 void
    833 nchreinit(void)
    834 {
    835 	struct namecache *ncp;
    836 	struct nchashhead *oldhash1, *hash1;
    837 	struct ncvhashhead *oldhash2, *hash2;
    838 	u_long i, oldmask1, oldmask2, mask1, mask2;
    839 
    840 	hash1 = hashinit(desiredvnodes, HASH_LIST, true, &mask1);
    841 	hash2 =
    842 #ifdef NAMECACHE_ENTER_REVERSE
    843 	    hashinit(desiredvnodes, HASH_LIST, true, &mask2);
    844 #else
    845 	    hashinit(desiredvnodes/8, HASH_LIST, true, &mask2);
    846 #endif
    847 	mutex_enter(namecache_lock);
    848 	cache_lock_cpus();
    849 	oldhash1 = nchashtbl;
    850 	oldmask1 = nchash;
    851 	nchashtbl = hash1;
    852 	nchash = mask1;
    853 	oldhash2 = ncvhashtbl;
    854 	oldmask2 = ncvhash;
    855 	ncvhashtbl = hash2;
    856 	ncvhash = mask2;
    857 	for (i = 0; i <= oldmask1; i++) {
    858 		while ((ncp = LIST_FIRST(&oldhash1[i])) != NULL) {
    859 			LIST_REMOVE(ncp, nc_hash);
    860 			ncp->nc_hash.le_prev = NULL;
    861 		}
    862 	}
    863 	for (i = 0; i <= oldmask2; i++) {
    864 		while ((ncp = LIST_FIRST(&oldhash2[i])) != NULL) {
    865 			LIST_REMOVE(ncp, nc_vhash);
    866 			ncp->nc_vhash.le_prev = NULL;
    867 		}
    868 	}
    869 	cache_unlock_cpus();
    870 	mutex_exit(namecache_lock);
    871 	hashdone(oldhash1, HASH_LIST, oldmask1);
    872 	hashdone(oldhash2, HASH_LIST, oldmask2);
    873 }
    874 
    875 /*
    876  * Cache flush, a particular vnode; called when a vnode is renamed to
    877  * hide entries that would now be invalid
    878  */
    879 void
    880 cache_purge1(struct vnode *vp, const char *name, size_t namelen, int flags)
    881 {
    882 	struct namecache *ncp, *ncnext;
    883 
    884 	mutex_enter(namecache_lock);
    885 	if (flags & PURGE_PARENTS) {
    886 		for (ncp = LIST_FIRST(&vp->v_nclist); ncp != NULL;
    887 		    ncp = ncnext) {
    888 			ncnext = LIST_NEXT(ncp, nc_vlist);
    889 			mutex_enter(&ncp->nc_lock);
    890 			cache_invalidate(ncp);
    891 			mutex_exit(&ncp->nc_lock);
    892 			cache_disassociate(ncp);
    893 		}
    894 	}
    895 	if (flags & PURGE_CHILDREN) {
    896 		for (ncp = LIST_FIRST(&vp->v_dnclist); ncp != NULL;
    897 		    ncp = ncnext) {
    898 			ncnext = LIST_NEXT(ncp, nc_dvlist);
    899 			mutex_enter(&ncp->nc_lock);
    900 			cache_invalidate(ncp);
    901 			mutex_exit(&ncp->nc_lock);
    902 			cache_disassociate(ncp);
    903 		}
    904 	}
    905 	if (name != NULL) {
    906 		ncp = cache_lookup_entry(vp, name, namelen);
    907 		if (ncp) {
    908 			cache_invalidate(ncp);
    909 			mutex_exit(&ncp->nc_lock);
    910 			cache_disassociate(ncp);
    911 		}
    912 	}
    913 	mutex_exit(namecache_lock);
    914 }
    915 
    916 /*
    917  * Cache flush, a whole filesystem; called when filesys is umounted to
    918  * remove entries that would now be invalid.
    919  */
    920 void
    921 cache_purgevfs(struct mount *mp)
    922 {
    923 	struct namecache *ncp, *nxtcp;
    924 
    925 	mutex_enter(namecache_lock);
    926 	for (ncp = TAILQ_FIRST(&nclruhead); ncp != NULL; ncp = nxtcp) {
    927 		nxtcp = TAILQ_NEXT(ncp, nc_lru);
    928 		mutex_enter(&ncp->nc_lock);
    929 		if (ncp->nc_dvp != NULL && ncp->nc_dvp->v_mount == mp) {
    930 			/* Free the resources we had. */
    931 			cache_invalidate(ncp);
    932 			cache_disassociate(ncp);
    933 		}
    934 		mutex_exit(&ncp->nc_lock);
    935 	}
    936 	cache_reclaim();
    937 	mutex_exit(namecache_lock);
    938 }
    939 
    940 /*
    941  * Scan global list invalidating entries until we meet a preset target.
    942  * Prefer to invalidate entries that have not scored a hit within
    943  * cache_hottime seconds.  We sort the LRU list only for this routine's
    944  * benefit.
    945  */
    946 static void
    947 cache_prune(int incache, int target)
    948 {
    949 	struct namecache *ncp, *nxtcp, *sentinel;
    950 	int items, recent, tryharder;
    951 
    952 	KASSERT(mutex_owned(namecache_lock));
    953 
    954 	items = 0;
    955 	tryharder = 0;
    956 	recent = hardclock_ticks - hz * cache_hottime;
    957 	sentinel = NULL;
    958 	for (ncp = TAILQ_FIRST(&nclruhead); ncp != NULL; ncp = nxtcp) {
    959 		if (incache <= target)
    960 			break;
    961 		items++;
    962 		nxtcp = TAILQ_NEXT(ncp, nc_lru);
    963 		if (ncp == sentinel) {
    964 			/*
    965 			 * If we looped back on ourself, then ignore
    966 			 * recent entries and purge whatever we find.
    967 			 */
    968 			tryharder = 1;
    969 		}
    970 		if (ncp->nc_dvp == NULL)
    971 			continue;
    972 		if (!tryharder && (ncp->nc_hittime - recent) > 0) {
    973 			if (sentinel == NULL)
    974 				sentinel = ncp;
    975 			TAILQ_REMOVE(&nclruhead, ncp, nc_lru);
    976 			TAILQ_INSERT_TAIL(&nclruhead, ncp, nc_lru);
    977 			continue;
    978 		}
    979 		mutex_enter(&ncp->nc_lock);
    980 		if (ncp->nc_dvp != NULL) {
    981 			cache_invalidate(ncp);
    982 			cache_disassociate(ncp);
    983 			incache--;
    984 		}
    985 		mutex_exit(&ncp->nc_lock);
    986 	}
    987 	cache_ev_scan.ev_count += items;
    988 }
    989 
    990 /*
    991  * Collect dead cache entries from all CPUs and garbage collect.
    992  */
    993 static void
    994 cache_reclaim(void)
    995 {
    996 	struct namecache *ncp, *next;
    997 	int items;
    998 
    999 	KASSERT(mutex_owned(namecache_lock));
   1000 
   1001 	/*
   1002 	 * If the number of extant entries not awaiting garbage collection
   1003 	 * exceeds the high water mark, then reclaim stale entries until we
   1004 	 * reach our low water mark.
   1005 	 */
   1006 	items = numcache - cache_gcpend;
   1007 	if (items > (uint64_t)desiredvnodes * cache_hiwat / 100) {
   1008 		cache_prune(items, (int)((uint64_t)desiredvnodes *
   1009 		    cache_lowat / 100));
   1010 		cache_ev_over.ev_count++;
   1011 	} else
   1012 		cache_ev_under.ev_count++;
   1013 
   1014 	/*
   1015 	 * Stop forward lookup activity on all CPUs and garbage collect dead
   1016 	 * entries.
   1017 	 */
   1018 	cache_lock_cpus();
   1019 	ncp = cache_gcqueue;
   1020 	cache_gcqueue = NULL;
   1021 	items = cache_gcpend;
   1022 	cache_gcpend = 0;
   1023 	while (ncp != NULL) {
   1024 		next = ncp->nc_gcqueue;
   1025 		cache_disassociate(ncp);
   1026 		KASSERT(ncp->nc_dvp == NULL);
   1027 		if (ncp->nc_hash.le_prev != NULL) {
   1028 			LIST_REMOVE(ncp, nc_hash);
   1029 			ncp->nc_hash.le_prev = NULL;
   1030 		}
   1031 		pool_cache_put(namecache_cache, ncp);
   1032 		ncp = next;
   1033 	}
   1034 	cache_unlock_cpus();
   1035 	numcache -= items;
   1036 	cache_ev_gc.ev_count += items;
   1037 }
   1038 
   1039 /*
   1040  * Cache maintainence thread, awakening once per second to:
   1041  *
   1042  * => keep number of entries below the high water mark
   1043  * => sort pseudo-LRU list
   1044  * => garbage collect dead entries
   1045  */
   1046 static void
   1047 cache_thread(void *arg)
   1048 {
   1049 
   1050 	mutex_enter(namecache_lock);
   1051 	for (;;) {
   1052 		cache_reclaim();
   1053 		kpause("cachegc", false, hz, namecache_lock);
   1054 	}
   1055 }
   1056 
   1057 #ifdef DDB
   1058 void
   1059 namecache_print(struct vnode *vp, void (*pr)(const char *, ...))
   1060 {
   1061 	struct vnode *dvp = NULL;
   1062 	struct namecache *ncp;
   1063 
   1064 	TAILQ_FOREACH(ncp, &nclruhead, nc_lru) {
   1065 		if (ncp->nc_vp == vp && ncp->nc_dvp != NULL) {
   1066 			(*pr)("name %.*s\n", ncp->nc_nlen, ncp->nc_name);
   1067 			dvp = ncp->nc_dvp;
   1068 		}
   1069 	}
   1070 	if (dvp == NULL) {
   1071 		(*pr)("name not found\n");
   1072 		return;
   1073 	}
   1074 	vp = dvp;
   1075 	TAILQ_FOREACH(ncp, &nclruhead, nc_lru) {
   1076 		if (ncp->nc_vp == vp) {
   1077 			(*pr)("parent %.*s\n", ncp->nc_nlen, ncp->nc_name);
   1078 		}
   1079 	}
   1080 }
   1081 #endif
   1082 
   1083 void
   1084 namecache_count_pass2(void)
   1085 {
   1086 	struct nchcpu *cpup = curcpu()->ci_data.cpu_nch;
   1087 
   1088 	mutex_enter(&cpup->cpu_lock);
   1089 	COUNT(cpup->cpu_stats, ncs_pass2);
   1090 	mutex_exit(&cpup->cpu_lock);
   1091 }
   1092 
   1093 void
   1094 namecache_count_2passes(void)
   1095 {
   1096 	struct nchcpu *cpup = curcpu()->ci_data.cpu_nch;
   1097 
   1098 	mutex_enter(&cpup->cpu_lock);
   1099 	COUNT(cpup->cpu_stats, ncs_2passes);
   1100 	mutex_exit(&cpup->cpu_lock);
   1101 }
   1102 
   1103 static int
   1104 cache_stat_sysctl(SYSCTLFN_ARGS)
   1105 {
   1106 	struct nchstats_sysctl stats;
   1107 
   1108 	if (oldp == NULL) {
   1109 		*oldlenp = sizeof(stats);
   1110 		return 0;
   1111 	}
   1112 
   1113 	if (*oldlenp < sizeof(stats)) {
   1114 		*oldlenp = 0;
   1115 		return 0;
   1116 	}
   1117 
   1118 	memset(&stats, 0, sizeof(stats));
   1119 
   1120 	sysctl_unlock();
   1121 	cache_lock_cpus();
   1122 	stats.ncs_goodhits = nchstats.ncs_goodhits;
   1123 	stats.ncs_neghits = nchstats.ncs_neghits;
   1124 	stats.ncs_badhits = nchstats.ncs_badhits;
   1125 	stats.ncs_falsehits = nchstats.ncs_falsehits;
   1126 	stats.ncs_miss = nchstats.ncs_miss;
   1127 	stats.ncs_long = nchstats.ncs_long;
   1128 	stats.ncs_pass2 = nchstats.ncs_pass2;
   1129 	stats.ncs_2passes = nchstats.ncs_2passes;
   1130 	stats.ncs_revhits = nchstats.ncs_revhits;
   1131 	stats.ncs_revmiss = nchstats.ncs_revmiss;
   1132 	cache_unlock_cpus();
   1133 	sysctl_relock();
   1134 
   1135 	*oldlenp = sizeof(stats);
   1136 	return sysctl_copyout(l, &stats, oldp, sizeof(stats));
   1137 }
   1138 
   1139 SYSCTL_SETUP(sysctl_cache_stat_setup, "vfs.namecache_stats subtree setup")
   1140 {
   1141 	sysctl_createv(clog, 0, NULL, NULL,
   1142 		       CTLFLAG_PERMANENT,
   1143 		       CTLTYPE_STRUCT, "namecache_stats",
   1144 		       SYSCTL_DESCR("namecache statistics"),
   1145 		       cache_stat_sysctl, 0, NULL, 0,
   1146 		       CTL_VFS, CTL_CREATE, CTL_EOL);
   1147 }
   1148