Home | History | Annotate | Line # | Download | only in kern
vfs_vnode.c revision 1.82
      1 /*	$NetBSD: vfs_vnode.c,v 1.82 2017/04/11 14:25:00 riastradh Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997-2011 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center, by Charles M. Hannum, and by Andrew Doran.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  *
     20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     30  * POSSIBILITY OF SUCH DAMAGE.
     31  */
     32 
     33 /*
     34  * Copyright (c) 1989, 1993
     35  *	The Regents of the University of California.  All rights reserved.
     36  * (c) UNIX System Laboratories, Inc.
     37  * All or some portions of this file are derived from material licensed
     38  * to the University of California by American Telephone and Telegraph
     39  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
     40  * the permission of UNIX System Laboratories, Inc.
     41  *
     42  * Redistribution and use in source and binary forms, with or without
     43  * modification, are permitted provided that the following conditions
     44  * are met:
     45  * 1. Redistributions of source code must retain the above copyright
     46  *    notice, this list of conditions and the following disclaimer.
     47  * 2. Redistributions in binary form must reproduce the above copyright
     48  *    notice, this list of conditions and the following disclaimer in the
     49  *    documentation and/or other materials provided with the distribution.
     50  * 3. Neither the name of the University nor the names of its contributors
     51  *    may be used to endorse or promote products derived from this software
     52  *    without specific prior written permission.
     53  *
     54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     64  * SUCH DAMAGE.
     65  *
     66  *	@(#)vfs_subr.c	8.13 (Berkeley) 4/18/94
     67  */
     68 
     69 /*
     70  * The vnode cache subsystem.
     71  *
     72  * Life-cycle
     73  *
     74  *	Normally, there are two points where new vnodes are created:
     75  *	VOP_CREATE(9) and VOP_LOOKUP(9).  The life-cycle of a vnode
     76  *	starts in one of the following ways:
     77  *
     78  *	- Allocation, via vcache_get(9) or vcache_new(9).
     79  *	- Reclamation of inactive vnode, via vcache_vget(9).
     80  *
     81  *	Recycle from a free list, via getnewvnode(9) -> getcleanvnode(9)
     82  *	was another, traditional way.  Currently, only the draining thread
     83  *	recycles the vnodes.  This behaviour might be revisited.
     84  *
     85  *	The life-cycle ends when the last reference is dropped, usually
     86  *	in VOP_REMOVE(9).  In such case, VOP_INACTIVE(9) is called to inform
     87  *	the file system that vnode is inactive.  Via this call, file system
     88  *	indicates whether vnode can be recycled (usually, it checks its own
     89  *	references, e.g. count of links, whether the file was removed).
     90  *
     91  *	Depending on indication, vnode can be put into a free list (cache),
     92  *	or cleaned via vcache_reclaim, which calls VOP_RECLAIM(9) to
     93  *	disassociate underlying file system from the vnode, and finally
     94  *	destroyed.
     95  *
     96  * Vnode state
     97  *
     98  *	Vnode is always in one of six states:
     99  *	- MARKER	This is a marker vnode to help list traversal.  It
    100  *			will never change its state.
    101  *	- LOADING	Vnode is associating underlying file system and not
    102  *			yet ready to use.
    103  *	- ACTIVE	Vnode has associated underlying file system and is
    104  *			ready to use.
    105  *	- BLOCKED	Vnode is active but cannot get new references.
    106  *	- RECLAIMING	Vnode is disassociating from the underlying file
    107  *			system.
    108  *	- RECLAIMED	Vnode has disassociated from underlying file system
    109  *			and is dead.
    110  *
    111  *	Valid state changes are:
    112  *	LOADING -> ACTIVE
    113  *			Vnode has been initialised in vcache_get() or
    114  *			vcache_new() and is ready to use.
    115  *	ACTIVE -> RECLAIMING
    116  *			Vnode starts disassociation from underlying file
    117  *			system in vcache_reclaim().
    118  *	RECLAIMING -> RECLAIMED
    119  *			Vnode finished disassociation from underlying file
    120  *			system in vcache_reclaim().
    121  *	ACTIVE -> BLOCKED
    122  *			Either vcache_rekey*() is changing the vnode key or
    123  *			vrelel() is about to call VOP_INACTIVE().
    124  *	BLOCKED -> ACTIVE
    125  *			The block condition is over.
    126  *	LOADING -> RECLAIMED
    127  *			Either vcache_get() or vcache_new() failed to
    128  *			associate the underlying file system or vcache_rekey*()
    129  *			drops a vnode used as placeholder.
    130  *
    131  *	Of these states LOADING, BLOCKED and RECLAIMING are intermediate
    132  *	and it is possible to wait for state change.
    133  *
    134  *	State is protected with v_interlock with one exception:
    135  *	to change from LOADING both v_interlock and vcache_lock must be held
    136  *	so it is possible to check "state == LOADING" without holding
    137  *	v_interlock.  See vcache_get() for details.
    138  *
    139  * Reference counting
    140  *
    141  *	Vnode is considered active, if reference count (vnode_t::v_usecount)
    142  *	is non-zero.  It is maintained using: vref(9) and vrele(9), as well
    143  *	as vput(9), routines.  Common points holding references are e.g.
    144  *	file openings, current working directory, mount points, etc.
    145  *
    146  * Note on v_usecount and its locking
    147  *
    148  *	At nearly all points it is known that v_usecount could be zero,
    149  *	the vnode_t::v_interlock will be held.  To change v_usecount away
    150  *	from zero, the interlock must be held.  To change from a non-zero
    151  *	value to zero, again the interlock must be held.
    152  *
    153  *	Changing the usecount from a non-zero value to a non-zero value can
    154  *	safely be done using atomic operations, without the interlock held.
    155  *
    156  */
    157 
    158 #include <sys/cdefs.h>
    159 __KERNEL_RCSID(0, "$NetBSD: vfs_vnode.c,v 1.82 2017/04/11 14:25:00 riastradh Exp $");
    160 
    161 #include <sys/param.h>
    162 #include <sys/kernel.h>
    163 
    164 #include <sys/atomic.h>
    165 #include <sys/buf.h>
    166 #include <sys/conf.h>
    167 #include <sys/device.h>
    168 #include <sys/hash.h>
    169 #include <sys/kauth.h>
    170 #include <sys/kmem.h>
    171 #include <sys/kthread.h>
    172 #include <sys/module.h>
    173 #include <sys/mount.h>
    174 #include <sys/namei.h>
    175 #include <sys/syscallargs.h>
    176 #include <sys/sysctl.h>
    177 #include <sys/systm.h>
    178 #include <sys/vnode_impl.h>
    179 #include <sys/wapbl.h>
    180 #include <sys/fstrans.h>
    181 
    182 #include <uvm/uvm.h>
    183 #include <uvm/uvm_readahead.h>
    184 
    185 /* Flags to vrelel. */
    186 #define	VRELEL_ASYNC_RELE	0x0001	/* Always defer to vrele thread. */
    187 #define	VRELEL_FORCE_RELE	0x0002	/* Must always succeed. */
    188 
    189 u_int			numvnodes		__cacheline_aligned;
    190 
    191 /*
    192  * There are three lru lists: one holds vnodes waiting for async release,
    193  * one is for vnodes which have no buffer/page references and
    194  * one for those which do (i.e. v_holdcnt is non-zero).
    195  */
    196 static vnodelst_t	lru_vrele_list		__cacheline_aligned;
    197 static vnodelst_t	lru_free_list		__cacheline_aligned;
    198 static vnodelst_t	lru_hold_list		__cacheline_aligned;
    199 static kmutex_t		vdrain_lock		__cacheline_aligned;
    200 static kcondvar_t	vdrain_cv		__cacheline_aligned;
    201 static int		vdrain_gen;
    202 static kcondvar_t	vdrain_gen_cv;
    203 static bool		vdrain_retry;
    204 static lwp_t *		vdrain_lwp;
    205 SLIST_HEAD(hashhead, vnode_impl);
    206 static kmutex_t		vcache_lock		__cacheline_aligned;
    207 static kcondvar_t	vcache_cv		__cacheline_aligned;
    208 static u_int		vcache_hashsize;
    209 static u_long		vcache_hashmask;
    210 static struct hashhead	*vcache_hashtab		__cacheline_aligned;
    211 static pool_cache_t	vcache_pool;
    212 static void		lru_requeue(vnode_t *, vnodelst_t *);
    213 static vnodelst_t *	lru_which(vnode_t *);
    214 static vnode_impl_t *	vcache_alloc(void);
    215 static void		vcache_dealloc(vnode_impl_t *);
    216 static void		vcache_free(vnode_impl_t *);
    217 static void		vcache_init(void);
    218 static void		vcache_reinit(void);
    219 static void		vcache_reclaim(vnode_t *);
    220 static void		vrelel(vnode_t *, int);
    221 static void		vdrain_thread(void *);
    222 static void		vnpanic(vnode_t *, const char *, ...)
    223     __printflike(2, 3);
    224 
    225 /* Routines having to do with the management of the vnode table. */
    226 extern struct mount	*dead_rootmount;
    227 extern int		(**dead_vnodeop_p)(void *);
    228 extern struct vfsops	dead_vfsops;
    229 
    230 /* Vnode state operations and diagnostics. */
    231 
    232 #if defined(DIAGNOSTIC)
    233 
    234 #define VSTATE_GET(vp) \
    235 	vstate_assert_get((vp), __func__, __LINE__)
    236 #define VSTATE_CHANGE(vp, from, to) \
    237 	vstate_assert_change((vp), (from), (to), __func__, __LINE__)
    238 #define VSTATE_WAIT_STABLE(vp) \
    239 	vstate_assert_wait_stable((vp), __func__, __LINE__)
    240 #define VSTATE_ASSERT(vp, state) \
    241 	vstate_assert((vp), (state), __func__, __LINE__)
    242 
    243 static void
    244 vstate_assert(vnode_t *vp, enum vnode_state state, const char *func, int line)
    245 {
    246 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    247 
    248 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    249 
    250 	if (__predict_true(vip->vi_state == state))
    251 		return;
    252 	vnpanic(vp, "state is %s, expected %s at %s:%d",
    253 	    vstate_name(vip->vi_state), vstate_name(state), func, line);
    254 }
    255 
    256 static enum vnode_state
    257 vstate_assert_get(vnode_t *vp, const char *func, int line)
    258 {
    259 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    260 
    261 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    262 	if (vip->vi_state == VS_MARKER)
    263 		vnpanic(vp, "state is %s at %s:%d",
    264 		    vstate_name(vip->vi_state), func, line);
    265 
    266 	return vip->vi_state;
    267 }
    268 
    269 static void
    270 vstate_assert_wait_stable(vnode_t *vp, const char *func, int line)
    271 {
    272 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    273 
    274 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    275 	if (vip->vi_state == VS_MARKER)
    276 		vnpanic(vp, "state is %s at %s:%d",
    277 		    vstate_name(vip->vi_state), func, line);
    278 
    279 	while (vip->vi_state != VS_ACTIVE && vip->vi_state != VS_RECLAIMED)
    280 		cv_wait(&vp->v_cv, vp->v_interlock);
    281 
    282 	if (vip->vi_state == VS_MARKER)
    283 		vnpanic(vp, "state is %s at %s:%d",
    284 		    vstate_name(vip->vi_state), func, line);
    285 }
    286 
    287 static void
    288 vstate_assert_change(vnode_t *vp, enum vnode_state from, enum vnode_state to,
    289     const char *func, int line)
    290 {
    291 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    292 
    293 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    294 	if (from == VS_LOADING)
    295 		KASSERTMSG(mutex_owned(&vcache_lock), "at %s:%d", func, line);
    296 
    297 	if (from == VS_MARKER)
    298 		vnpanic(vp, "from is %s at %s:%d",
    299 		    vstate_name(from), func, line);
    300 	if (to == VS_MARKER)
    301 		vnpanic(vp, "to is %s at %s:%d",
    302 		    vstate_name(to), func, line);
    303 	if (vip->vi_state != from)
    304 		vnpanic(vp, "from is %s, expected %s at %s:%d\n",
    305 		    vstate_name(vip->vi_state), vstate_name(from), func, line);
    306 	if ((from == VS_BLOCKED || to == VS_BLOCKED) && vp->v_usecount != 1)
    307 		vnpanic(vp, "%s to %s with usecount %d at %s:%d",
    308 		    vstate_name(from), vstate_name(to), vp->v_usecount,
    309 		    func, line);
    310 
    311 	vip->vi_state = to;
    312 	if (from == VS_LOADING)
    313 		cv_broadcast(&vcache_cv);
    314 	if (to == VS_ACTIVE || to == VS_RECLAIMED)
    315 		cv_broadcast(&vp->v_cv);
    316 }
    317 
    318 #else /* defined(DIAGNOSTIC) */
    319 
    320 #define VSTATE_GET(vp) \
    321 	(VNODE_TO_VIMPL((vp))->vi_state)
    322 #define VSTATE_CHANGE(vp, from, to) \
    323 	vstate_change((vp), (from), (to))
    324 #define VSTATE_WAIT_STABLE(vp) \
    325 	vstate_wait_stable((vp))
    326 #define VSTATE_ASSERT(vp, state)
    327 
    328 static void
    329 vstate_wait_stable(vnode_t *vp)
    330 {
    331 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    332 
    333 	while (vip->vi_state != VS_ACTIVE && vip->vi_state != VS_RECLAIMED)
    334 		cv_wait(&vp->v_cv, vp->v_interlock);
    335 }
    336 
    337 static void
    338 vstate_change(vnode_t *vp, enum vnode_state from, enum vnode_state to)
    339 {
    340 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    341 
    342 	vip->vi_state = to;
    343 	if (from == VS_LOADING)
    344 		cv_broadcast(&vcache_cv);
    345 	if (to == VS_ACTIVE || to == VS_RECLAIMED)
    346 		cv_broadcast(&vp->v_cv);
    347 }
    348 
    349 #endif /* defined(DIAGNOSTIC) */
    350 
    351 void
    352 vfs_vnode_sysinit(void)
    353 {
    354 	int error __diagused;
    355 
    356 	dead_rootmount = vfs_mountalloc(&dead_vfsops, NULL);
    357 	KASSERT(dead_rootmount != NULL);
    358 	dead_rootmount->mnt_iflag = IMNT_MPSAFE;
    359 
    360 	mutex_init(&vdrain_lock, MUTEX_DEFAULT, IPL_NONE);
    361 	TAILQ_INIT(&lru_free_list);
    362 	TAILQ_INIT(&lru_hold_list);
    363 	TAILQ_INIT(&lru_vrele_list);
    364 
    365 	vcache_init();
    366 
    367 	cv_init(&vdrain_cv, "vdrain");
    368 	cv_init(&vdrain_gen_cv, "vdrainwt");
    369 	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, vdrain_thread,
    370 	    NULL, &vdrain_lwp, "vdrain");
    371 	KASSERTMSG((error == 0), "kthread_create(vdrain) failed: %d", error);
    372 }
    373 
    374 /*
    375  * Allocate a new marker vnode.
    376  */
    377 vnode_t *
    378 vnalloc_marker(struct mount *mp)
    379 {
    380 	vnode_impl_t *vip;
    381 	vnode_t *vp;
    382 
    383 	vip = pool_cache_get(vcache_pool, PR_WAITOK);
    384 	memset(vip, 0, sizeof(*vip));
    385 	vp = VIMPL_TO_VNODE(vip);
    386 	uvm_obj_init(&vp->v_uobj, &uvm_vnodeops, true, 0);
    387 	vp->v_mount = mp;
    388 	vp->v_type = VBAD;
    389 	vip->vi_state = VS_MARKER;
    390 
    391 	return vp;
    392 }
    393 
    394 /*
    395  * Free a marker vnode.
    396  */
    397 void
    398 vnfree_marker(vnode_t *vp)
    399 {
    400 	vnode_impl_t *vip;
    401 
    402 	vip = VNODE_TO_VIMPL(vp);
    403 	KASSERT(vip->vi_state == VS_MARKER);
    404 	uvm_obj_destroy(&vp->v_uobj, true);
    405 	pool_cache_put(vcache_pool, vip);
    406 }
    407 
    408 /*
    409  * Test a vnode for being a marker vnode.
    410  */
    411 bool
    412 vnis_marker(vnode_t *vp)
    413 {
    414 
    415 	return (VNODE_TO_VIMPL(vp)->vi_state == VS_MARKER);
    416 }
    417 
    418 /*
    419  * Set vnode to share another vnodes lock.
    420  */
    421 void
    422 vshare_lock(vnode_t *vp, vnode_t *src_vp)
    423 {
    424 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    425 	vnode_impl_t *src_vip = VNODE_TO_VIMPL(src_vp);
    426 	krwlock_t *oldlock = vip->vi_lock;
    427 
    428 	rw_obj_hold(src_vip->vi_lock);
    429 	vip->vi_lock = src_vip->vi_lock;
    430 	rw_obj_free(oldlock);
    431 }
    432 
    433 /*
    434  * Return the lru list this node should be on.
    435  */
    436 static vnodelst_t *
    437 lru_which(vnode_t *vp)
    438 {
    439 
    440 	KASSERT(mutex_owned(vp->v_interlock));
    441 
    442 	if (vp->v_holdcnt > 0)
    443 		return &lru_hold_list;
    444 	else
    445 		return &lru_free_list;
    446 }
    447 
    448 /*
    449  * Put vnode to end of given list.
    450  * Both the current and the new list may be NULL, used on vnode alloc/free.
    451  * Adjust numvnodes and signal vdrain thread if there is work.
    452  */
    453 static void
    454 lru_requeue(vnode_t *vp, vnodelst_t *listhd)
    455 {
    456 	vnode_impl_t *vip;
    457 
    458 	mutex_enter(&vdrain_lock);
    459 	vip = VNODE_TO_VIMPL(vp);
    460 	if (vip->vi_lrulisthd != NULL)
    461 		TAILQ_REMOVE(vip->vi_lrulisthd, vip, vi_lrulist);
    462 	else
    463 		numvnodes++;
    464 	vip->vi_lrulisthd = listhd;
    465 	if (vip->vi_lrulisthd != NULL)
    466 		TAILQ_INSERT_TAIL(vip->vi_lrulisthd, vip, vi_lrulist);
    467 	else
    468 		numvnodes--;
    469 	if (numvnodes > desiredvnodes || listhd == &lru_vrele_list)
    470 		cv_broadcast(&vdrain_cv);
    471 	mutex_exit(&vdrain_lock);
    472 }
    473 
    474 /*
    475  * Release deferred vrele vnodes for this mount.
    476  * Called with file system suspended.
    477  */
    478 void
    479 vrele_flush(struct mount *mp)
    480 {
    481 	vnode_impl_t *vip, *marker;
    482 
    483 	KASSERT(fstrans_is_owner(mp));
    484 
    485 	marker = VNODE_TO_VIMPL(vnalloc_marker(NULL));
    486 
    487 	mutex_enter(&vdrain_lock);
    488 	TAILQ_INSERT_HEAD(&lru_vrele_list, marker, vi_lrulist);
    489 
    490 	while ((vip = TAILQ_NEXT(marker, vi_lrulist))) {
    491 		TAILQ_REMOVE(&lru_vrele_list, marker, vi_lrulist);
    492 		TAILQ_INSERT_AFTER(&lru_vrele_list, vip, marker, vi_lrulist);
    493 		if (vnis_marker(VIMPL_TO_VNODE(vip)))
    494 			continue;
    495 
    496 		KASSERT(vip->vi_lrulisthd == &lru_vrele_list);
    497 		TAILQ_REMOVE(vip->vi_lrulisthd, vip, vi_lrulist);
    498 		vip->vi_lrulisthd = &lru_hold_list;
    499 		TAILQ_INSERT_TAIL(vip->vi_lrulisthd, vip, vi_lrulist);
    500 		mutex_exit(&vdrain_lock);
    501 
    502 		mutex_enter(VIMPL_TO_VNODE(vip)->v_interlock);
    503 		vrelel(VIMPL_TO_VNODE(vip), VRELEL_FORCE_RELE);
    504 
    505 		mutex_enter(&vdrain_lock);
    506 	}
    507 
    508 	TAILQ_REMOVE(&lru_vrele_list, marker, vi_lrulist);
    509 	mutex_exit(&vdrain_lock);
    510 
    511 	vnfree_marker(VIMPL_TO_VNODE(marker));
    512 }
    513 
    514 /*
    515  * Reclaim a cached vnode.  Used from vdrain_thread only.
    516  */
    517 static __inline void
    518 vdrain_remove(vnode_t *vp)
    519 {
    520 	struct mount *mp;
    521 
    522 	KASSERT(mutex_owned(&vdrain_lock));
    523 
    524 	/* Probe usecount (unlocked). */
    525 	if (vp->v_usecount > 0)
    526 		return;
    527 	/* Try v_interlock -- we lock the wrong direction! */
    528 	if (!mutex_tryenter(vp->v_interlock))
    529 		return;
    530 	/* Probe usecount and state. */
    531 	if (vp->v_usecount > 0 || VSTATE_GET(vp) != VS_ACTIVE) {
    532 		mutex_exit(vp->v_interlock);
    533 		return;
    534 	}
    535 	mp = vp->v_mount;
    536 	if (fstrans_start_nowait(mp, FSTRANS_SHARED) != 0) {
    537 		mutex_exit(vp->v_interlock);
    538 		return;
    539 	}
    540 	vdrain_retry = true;
    541 	mutex_exit(&vdrain_lock);
    542 
    543 	if (vcache_vget(vp) == 0) {
    544 		if (!vrecycle(vp)) {
    545 			mutex_enter(vp->v_interlock);
    546 			vrelel(vp, VRELEL_FORCE_RELE);
    547 		}
    548 	}
    549 	fstrans_done(mp);
    550 
    551 	mutex_enter(&vdrain_lock);
    552 }
    553 
    554 /*
    555  * Release a cached vnode.  Used from vdrain_thread only.
    556  */
    557 static __inline void
    558 vdrain_vrele(vnode_t *vp)
    559 {
    560 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
    561 	struct mount *mp;
    562 
    563 	KASSERT(mutex_owned(&vdrain_lock));
    564 
    565 	mp = vp->v_mount;
    566 	if (fstrans_start_nowait(mp, FSTRANS_SHARED) != 0)
    567 		return;
    568 
    569 	/*
    570 	 * First remove the vnode from the vrele list.
    571 	 * Put it on the last lru list, the last vrele()
    572 	 * will put it back onto the right list before
    573 	 * its v_usecount reaches zero.
    574 	 */
    575 	KASSERT(vip->vi_lrulisthd == &lru_vrele_list);
    576 	TAILQ_REMOVE(vip->vi_lrulisthd, vip, vi_lrulist);
    577 	vip->vi_lrulisthd = &lru_hold_list;
    578 	TAILQ_INSERT_TAIL(vip->vi_lrulisthd, vip, vi_lrulist);
    579 
    580 	vdrain_retry = true;
    581 	mutex_exit(&vdrain_lock);
    582 
    583 	mutex_enter(vp->v_interlock);
    584 	vrelel(vp, VRELEL_FORCE_RELE);
    585 	fstrans_done(mp);
    586 
    587 	mutex_enter(&vdrain_lock);
    588 }
    589 
    590 /*
    591  * Helper thread to keep the number of vnodes below desiredvnodes
    592  * and release vnodes from asynchronous vrele.
    593  */
    594 static void
    595 vdrain_thread(void *cookie)
    596 {
    597 	vnodelst_t *listhd[] = {
    598 	    &lru_vrele_list, &lru_free_list, &lru_hold_list
    599 	};
    600 	int i;
    601 	u_int target;
    602 	vnode_impl_t *vip, *marker;
    603 
    604 	marker = VNODE_TO_VIMPL(vnalloc_marker(NULL));
    605 
    606 	mutex_enter(&vdrain_lock);
    607 
    608 	for (;;) {
    609 		vdrain_retry = false;
    610 		target = desiredvnodes - desiredvnodes/10;
    611 
    612 		for (i = 0; i < __arraycount(listhd); i++) {
    613 			TAILQ_INSERT_HEAD(listhd[i], marker, vi_lrulist);
    614 			while ((vip = TAILQ_NEXT(marker, vi_lrulist))) {
    615 				TAILQ_REMOVE(listhd[i], marker, vi_lrulist);
    616 				TAILQ_INSERT_AFTER(listhd[i], vip, marker,
    617 				    vi_lrulist);
    618 				if (vnis_marker(VIMPL_TO_VNODE(vip)))
    619 					continue;
    620 				if (listhd[i] == &lru_vrele_list)
    621 					vdrain_vrele(VIMPL_TO_VNODE(vip));
    622 				else if (numvnodes < target)
    623 					break;
    624 				else
    625 					vdrain_remove(VIMPL_TO_VNODE(vip));
    626 			}
    627 			TAILQ_REMOVE(listhd[i], marker, vi_lrulist);
    628 		}
    629 
    630 		if (vdrain_retry) {
    631 			mutex_exit(&vdrain_lock);
    632 			yield();
    633 			mutex_enter(&vdrain_lock);
    634 		} else {
    635 			vdrain_gen++;
    636 			cv_broadcast(&vdrain_gen_cv);
    637 			cv_wait(&vdrain_cv, &vdrain_lock);
    638 		}
    639 	}
    640 }
    641 
    642 /*
    643  * vput: unlock and release the reference.
    644  */
    645 void
    646 vput(vnode_t *vp)
    647 {
    648 
    649 	VOP_UNLOCK(vp);
    650 	vrele(vp);
    651 }
    652 
    653 /*
    654  * Try to drop reference on a vnode.  Abort if we are releasing the
    655  * last reference.  Note: this _must_ succeed if not the last reference.
    656  */
    657 static inline bool
    658 vtryrele(vnode_t *vp)
    659 {
    660 	u_int use, next;
    661 
    662 	for (use = vp->v_usecount;; use = next) {
    663 		if (use == 1) {
    664 			return false;
    665 		}
    666 		KASSERT(use > 1);
    667 		next = atomic_cas_uint(&vp->v_usecount, use, use - 1);
    668 		if (__predict_true(next == use)) {
    669 			return true;
    670 		}
    671 	}
    672 }
    673 
    674 /*
    675  * Vnode release.  If reference count drops to zero, call inactive
    676  * routine and either return to freelist or free to the pool.
    677  */
    678 static void
    679 vrelel(vnode_t *vp, int flags)
    680 {
    681 	const bool async = ((flags & VRELEL_ASYNC_RELE) != 0);
    682 	const bool force = ((flags & VRELEL_FORCE_RELE) != 0);
    683 	bool recycle, defer;
    684 	int error;
    685 
    686 	KASSERT(mutex_owned(vp->v_interlock));
    687 
    688 	if (__predict_false(vp->v_op == dead_vnodeop_p &&
    689 	    VSTATE_GET(vp) != VS_RECLAIMED)) {
    690 		vnpanic(vp, "dead but not clean");
    691 	}
    692 
    693 	/*
    694 	 * If not the last reference, just drop the reference count
    695 	 * and unlock.
    696 	 */
    697 	if (vtryrele(vp)) {
    698 		mutex_exit(vp->v_interlock);
    699 		return;
    700 	}
    701 	if (vp->v_usecount <= 0 || vp->v_writecount != 0) {
    702 		vnpanic(vp, "%s: bad ref count", __func__);
    703 	}
    704 
    705 #ifdef DIAGNOSTIC
    706 	if ((vp->v_type == VBLK || vp->v_type == VCHR) &&
    707 	    vp->v_specnode != NULL && vp->v_specnode->sn_opencnt != 0) {
    708 		vprint("vrelel: missing VOP_CLOSE()", vp);
    709 	}
    710 #endif
    711 
    712 	/*
    713 	 * First try to get the vnode locked for VOP_INACTIVE().
    714 	 * Defer vnode release to vdrain_thread if caller requests
    715 	 * it explicitly, is the pagedaemon or the lock failed.
    716 	 */
    717 	if ((curlwp == uvm.pagedaemon_lwp) || async) {
    718 		defer = true;
    719 	} else {
    720 		mutex_exit(vp->v_interlock);
    721 		error = vn_lock(vp,
    722 		    LK_EXCLUSIVE | LK_RETRY | (force ? 0 : LK_NOWAIT));
    723 		defer = (error != 0);
    724 		mutex_enter(vp->v_interlock);
    725 	}
    726 	KASSERT(mutex_owned(vp->v_interlock));
    727 	KASSERT(! (force && defer));
    728 	if (defer) {
    729 		/*
    730 		 * Defer reclaim to the kthread; it's not safe to
    731 		 * clean it here.  We donate it our last reference.
    732 		 */
    733 		lru_requeue(vp, &lru_vrele_list);
    734 		mutex_exit(vp->v_interlock);
    735 		return;
    736 	}
    737 
    738 	/*
    739 	 * If the node got another reference while we
    740 	 * released the interlock, don't try to inactivate it yet.
    741 	 */
    742 	if (__predict_false(vtryrele(vp))) {
    743 		VOP_UNLOCK(vp);
    744 		mutex_exit(vp->v_interlock);
    745 		return;
    746 	}
    747 
    748 	/*
    749 	 * If not clean, deactivate the vnode, but preserve
    750 	 * our reference across the call to VOP_INACTIVE().
    751 	 */
    752 	if (VSTATE_GET(vp) == VS_RECLAIMED) {
    753 		VOP_UNLOCK(vp);
    754 	} else {
    755 		VSTATE_CHANGE(vp, VS_ACTIVE, VS_BLOCKED);
    756 		mutex_exit(vp->v_interlock);
    757 
    758 		/*
    759 		 * The vnode must not gain another reference while being
    760 		 * deactivated.  If VOP_INACTIVE() indicates that
    761 		 * the described file has been deleted, then recycle
    762 		 * the vnode.
    763 		 *
    764 		 * Note that VOP_INACTIVE() will not drop the vnode lock.
    765 		 */
    766 		recycle = false;
    767 		VOP_INACTIVE(vp, &recycle);
    768 		VOP_UNLOCK(vp);
    769 		if (recycle) {
    770 			/* vcache_reclaim() below will drop the lock. */
    771 			if (vn_lock(vp, LK_EXCLUSIVE) != 0)
    772 				recycle = false;
    773 		}
    774 		mutex_enter(vp->v_interlock);
    775 		VSTATE_CHANGE(vp, VS_BLOCKED, VS_ACTIVE);
    776 		if (!recycle) {
    777 			if (vtryrele(vp)) {
    778 				mutex_exit(vp->v_interlock);
    779 				return;
    780 			}
    781 		}
    782 
    783 		/* Take care of space accounting. */
    784 		if (vp->v_iflag & VI_EXECMAP) {
    785 			atomic_add_int(&uvmexp.execpages,
    786 			    -vp->v_uobj.uo_npages);
    787 			atomic_add_int(&uvmexp.filepages,
    788 			    vp->v_uobj.uo_npages);
    789 		}
    790 		vp->v_iflag &= ~(VI_TEXT|VI_EXECMAP|VI_WRMAP);
    791 		vp->v_vflag &= ~VV_MAPPED;
    792 
    793 		/*
    794 		 * Recycle the vnode if the file is now unused (unlinked),
    795 		 * otherwise just free it.
    796 		 */
    797 		if (recycle) {
    798 			VSTATE_ASSERT(vp, VS_ACTIVE);
    799 			vcache_reclaim(vp);
    800 		}
    801 		KASSERT(vp->v_usecount > 0);
    802 	}
    803 
    804 	if (atomic_dec_uint_nv(&vp->v_usecount) != 0) {
    805 		/* Gained another reference while being reclaimed. */
    806 		mutex_exit(vp->v_interlock);
    807 		return;
    808 	}
    809 
    810 	if (VSTATE_GET(vp) == VS_RECLAIMED && vp->v_holdcnt == 0) {
    811 		/*
    812 		 * It's clean so destroy it.  It isn't referenced
    813 		 * anywhere since it has been reclaimed.
    814 		 */
    815 		vcache_free(VNODE_TO_VIMPL(vp));
    816 	} else {
    817 		/*
    818 		 * Otherwise, put it back onto the freelist.  It
    819 		 * can't be destroyed while still associated with
    820 		 * a file system.
    821 		 */
    822 		lru_requeue(vp, lru_which(vp));
    823 		mutex_exit(vp->v_interlock);
    824 	}
    825 }
    826 
    827 void
    828 vrele(vnode_t *vp)
    829 {
    830 
    831 	if (vtryrele(vp)) {
    832 		return;
    833 	}
    834 	mutex_enter(vp->v_interlock);
    835 	vrelel(vp, 0);
    836 }
    837 
    838 /*
    839  * Asynchronous vnode release, vnode is released in different context.
    840  */
    841 void
    842 vrele_async(vnode_t *vp)
    843 {
    844 
    845 	if (vtryrele(vp)) {
    846 		return;
    847 	}
    848 	mutex_enter(vp->v_interlock);
    849 	vrelel(vp, VRELEL_ASYNC_RELE);
    850 }
    851 
    852 /*
    853  * Vnode reference, where a reference is already held by some other
    854  * object (for example, a file structure).
    855  */
    856 void
    857 vref(vnode_t *vp)
    858 {
    859 
    860 	KASSERT(vp->v_usecount != 0);
    861 
    862 	atomic_inc_uint(&vp->v_usecount);
    863 }
    864 
    865 /*
    866  * Page or buffer structure gets a reference.
    867  * Called with v_interlock held.
    868  */
    869 void
    870 vholdl(vnode_t *vp)
    871 {
    872 
    873 	KASSERT(mutex_owned(vp->v_interlock));
    874 
    875 	if (vp->v_holdcnt++ == 0 && vp->v_usecount == 0)
    876 		lru_requeue(vp, lru_which(vp));
    877 }
    878 
    879 /*
    880  * Page or buffer structure frees a reference.
    881  * Called with v_interlock held.
    882  */
    883 void
    884 holdrelel(vnode_t *vp)
    885 {
    886 
    887 	KASSERT(mutex_owned(vp->v_interlock));
    888 
    889 	if (vp->v_holdcnt <= 0) {
    890 		vnpanic(vp, "%s: holdcnt vp %p", __func__, vp);
    891 	}
    892 
    893 	vp->v_holdcnt--;
    894 	if (vp->v_holdcnt == 0 && vp->v_usecount == 0)
    895 		lru_requeue(vp, lru_which(vp));
    896 }
    897 
    898 /*
    899  * Recycle an unused vnode if caller holds the last reference.
    900  */
    901 bool
    902 vrecycle(vnode_t *vp)
    903 {
    904 	int error __diagused;
    905 
    906 	mutex_enter(vp->v_interlock);
    907 
    908 	/* Make sure we hold the last reference. */
    909 	VSTATE_WAIT_STABLE(vp);
    910 	if (vp->v_usecount != 1) {
    911 		mutex_exit(vp->v_interlock);
    912 		return false;
    913 	}
    914 
    915 	/* If the vnode is already clean we're done. */
    916 	if (VSTATE_GET(vp) != VS_ACTIVE) {
    917 		VSTATE_ASSERT(vp, VS_RECLAIMED);
    918 		vrelel(vp, 0);
    919 		return true;
    920 	}
    921 
    922 	/* Prevent further references until the vnode is locked. */
    923 	VSTATE_CHANGE(vp, VS_ACTIVE, VS_BLOCKED);
    924 	mutex_exit(vp->v_interlock);
    925 
    926 	/*
    927 	 * On a leaf file system this lock will always succeed as we hold
    928 	 * the last reference and prevent further references.
    929 	 * On layered file systems waiting for the lock would open a can of
    930 	 * deadlocks as the lower vnodes may have other active references.
    931 	 */
    932 	error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY | LK_NOWAIT);
    933 
    934 	mutex_enter(vp->v_interlock);
    935 	VSTATE_CHANGE(vp, VS_BLOCKED, VS_ACTIVE);
    936 
    937 	if (error) {
    938 		mutex_exit(vp->v_interlock);
    939 		return false;
    940 	}
    941 
    942 	KASSERT(vp->v_usecount == 1);
    943 	vcache_reclaim(vp);
    944 	vrelel(vp, 0);
    945 
    946 	return true;
    947 }
    948 
    949 /*
    950  * Eliminate all activity associated with the requested vnode
    951  * and with all vnodes aliased to the requested vnode.
    952  */
    953 void
    954 vrevoke(vnode_t *vp)
    955 {
    956 	vnode_t *vq;
    957 	enum vtype type;
    958 	dev_t dev;
    959 
    960 	KASSERT(vp->v_usecount > 0);
    961 
    962 	mutex_enter(vp->v_interlock);
    963 	VSTATE_WAIT_STABLE(vp);
    964 	if (VSTATE_GET(vp) == VS_RECLAIMED) {
    965 		mutex_exit(vp->v_interlock);
    966 		return;
    967 	} else if (vp->v_type != VBLK && vp->v_type != VCHR) {
    968 		atomic_inc_uint(&vp->v_usecount);
    969 		mutex_exit(vp->v_interlock);
    970 		vgone(vp);
    971 		return;
    972 	} else {
    973 		dev = vp->v_rdev;
    974 		type = vp->v_type;
    975 		mutex_exit(vp->v_interlock);
    976 	}
    977 
    978 	while (spec_node_lookup_by_dev(type, dev, &vq) == 0) {
    979 		vgone(vq);
    980 	}
    981 }
    982 
    983 /*
    984  * Eliminate all activity associated with a vnode in preparation for
    985  * reuse.  Drops a reference from the vnode.
    986  */
    987 void
    988 vgone(vnode_t *vp)
    989 {
    990 
    991 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    992 	mutex_enter(vp->v_interlock);
    993 	VSTATE_WAIT_STABLE(vp);
    994 	if (VSTATE_GET(vp) == VS_ACTIVE)
    995 		vcache_reclaim(vp);
    996 	VSTATE_ASSERT(vp, VS_RECLAIMED);
    997 	vrelel(vp, 0);
    998 }
    999 
   1000 static inline uint32_t
   1001 vcache_hash(const struct vcache_key *key)
   1002 {
   1003 	uint32_t hash = HASH32_BUF_INIT;
   1004 
   1005 	hash = hash32_buf(&key->vk_mount, sizeof(struct mount *), hash);
   1006 	hash = hash32_buf(key->vk_key, key->vk_key_len, hash);
   1007 	return hash;
   1008 }
   1009 
   1010 static void
   1011 vcache_init(void)
   1012 {
   1013 
   1014 	vcache_pool = pool_cache_init(sizeof(vnode_impl_t), 0, 0, 0,
   1015 	    "vcachepl", NULL, IPL_NONE, NULL, NULL, NULL);
   1016 	KASSERT(vcache_pool != NULL);
   1017 	mutex_init(&vcache_lock, MUTEX_DEFAULT, IPL_NONE);
   1018 	cv_init(&vcache_cv, "vcache");
   1019 	vcache_hashsize = desiredvnodes;
   1020 	vcache_hashtab = hashinit(desiredvnodes, HASH_SLIST, true,
   1021 	    &vcache_hashmask);
   1022 }
   1023 
   1024 static void
   1025 vcache_reinit(void)
   1026 {
   1027 	int i;
   1028 	uint32_t hash;
   1029 	u_long oldmask, newmask;
   1030 	struct hashhead *oldtab, *newtab;
   1031 	vnode_impl_t *vip;
   1032 
   1033 	newtab = hashinit(desiredvnodes, HASH_SLIST, true, &newmask);
   1034 	mutex_enter(&vcache_lock);
   1035 	oldtab = vcache_hashtab;
   1036 	oldmask = vcache_hashmask;
   1037 	vcache_hashsize = desiredvnodes;
   1038 	vcache_hashtab = newtab;
   1039 	vcache_hashmask = newmask;
   1040 	for (i = 0; i <= oldmask; i++) {
   1041 		while ((vip = SLIST_FIRST(&oldtab[i])) != NULL) {
   1042 			SLIST_REMOVE(&oldtab[i], vip, vnode_impl, vi_hash);
   1043 			hash = vcache_hash(&vip->vi_key);
   1044 			SLIST_INSERT_HEAD(&newtab[hash & vcache_hashmask],
   1045 			    vip, vi_hash);
   1046 		}
   1047 	}
   1048 	mutex_exit(&vcache_lock);
   1049 	hashdone(oldtab, HASH_SLIST, oldmask);
   1050 }
   1051 
   1052 static inline vnode_impl_t *
   1053 vcache_hash_lookup(const struct vcache_key *key, uint32_t hash)
   1054 {
   1055 	struct hashhead *hashp;
   1056 	vnode_impl_t *vip;
   1057 
   1058 	KASSERT(mutex_owned(&vcache_lock));
   1059 
   1060 	hashp = &vcache_hashtab[hash & vcache_hashmask];
   1061 	SLIST_FOREACH(vip, hashp, vi_hash) {
   1062 		if (key->vk_mount != vip->vi_key.vk_mount)
   1063 			continue;
   1064 		if (key->vk_key_len != vip->vi_key.vk_key_len)
   1065 			continue;
   1066 		if (memcmp(key->vk_key, vip->vi_key.vk_key, key->vk_key_len))
   1067 			continue;
   1068 		return vip;
   1069 	}
   1070 	return NULL;
   1071 }
   1072 
   1073 /*
   1074  * Allocate a new, uninitialized vcache node.
   1075  */
   1076 static vnode_impl_t *
   1077 vcache_alloc(void)
   1078 {
   1079 	vnode_impl_t *vip;
   1080 	vnode_t *vp;
   1081 
   1082 	vip = pool_cache_get(vcache_pool, PR_WAITOK);
   1083 	memset(vip, 0, sizeof(*vip));
   1084 
   1085 	vip->vi_lock = rw_obj_alloc();
   1086 	/* SLIST_INIT(&vip->vi_hash); */
   1087 	/* LIST_INIT(&vip->vi_nclist); */
   1088 	/* LIST_INIT(&vip->vi_dnclist); */
   1089 
   1090 	vp = VIMPL_TO_VNODE(vip);
   1091 	uvm_obj_init(&vp->v_uobj, &uvm_vnodeops, true, 0);
   1092 	cv_init(&vp->v_cv, "vnode");
   1093 
   1094 	vp->v_usecount = 1;
   1095 	vp->v_type = VNON;
   1096 	vp->v_size = vp->v_writesize = VSIZENOTSET;
   1097 
   1098 	vip->vi_state = VS_LOADING;
   1099 
   1100 	lru_requeue(vp, &lru_free_list);
   1101 
   1102 	return vip;
   1103 }
   1104 
   1105 /*
   1106  * Deallocate a vcache node in state VS_LOADING.
   1107  *
   1108  * vcache_lock held on entry and released on return.
   1109  */
   1110 static void
   1111 vcache_dealloc(vnode_impl_t *vip)
   1112 {
   1113 	vnode_t *vp;
   1114 
   1115 	KASSERT(mutex_owned(&vcache_lock));
   1116 
   1117 	vp = VIMPL_TO_VNODE(vip);
   1118 	mutex_enter(vp->v_interlock);
   1119 	vp->v_op = dead_vnodeop_p;
   1120 	VSTATE_CHANGE(vp, VS_LOADING, VS_RECLAIMED);
   1121 	mutex_exit(&vcache_lock);
   1122 	vrelel(vp, 0);
   1123 }
   1124 
   1125 /*
   1126  * Free an unused, unreferenced vcache node.
   1127  * v_interlock locked on entry.
   1128  */
   1129 static void
   1130 vcache_free(vnode_impl_t *vip)
   1131 {
   1132 	vnode_t *vp;
   1133 
   1134 	vp = VIMPL_TO_VNODE(vip);
   1135 	KASSERT(mutex_owned(vp->v_interlock));
   1136 
   1137 	KASSERT(vp->v_usecount == 0);
   1138 	KASSERT(vp->v_holdcnt == 0);
   1139 	KASSERT(vp->v_writecount == 0);
   1140 	lru_requeue(vp, NULL);
   1141 	mutex_exit(vp->v_interlock);
   1142 
   1143 	vfs_insmntque(vp, NULL);
   1144 	if (vp->v_type == VBLK || vp->v_type == VCHR)
   1145 		spec_node_destroy(vp);
   1146 
   1147 	rw_obj_free(vip->vi_lock);
   1148 	uvm_obj_destroy(&vp->v_uobj, true);
   1149 	cv_destroy(&vp->v_cv);
   1150 	pool_cache_put(vcache_pool, vip);
   1151 }
   1152 
   1153 /*
   1154  * Try to get an initial reference on this cached vnode.
   1155  * Returns zero on success,  ENOENT if the vnode has been reclaimed and
   1156  * EBUSY if the vnode state is unstable.
   1157  *
   1158  * v_interlock locked on entry and unlocked on exit.
   1159  */
   1160 int
   1161 vcache_tryvget(vnode_t *vp)
   1162 {
   1163 	int error = 0;
   1164 
   1165 	KASSERT(mutex_owned(vp->v_interlock));
   1166 
   1167 	if (__predict_false(VSTATE_GET(vp) == VS_RECLAIMED))
   1168 		error = ENOENT;
   1169 	else if (__predict_false(VSTATE_GET(vp) != VS_ACTIVE))
   1170 		error = EBUSY;
   1171 	else if (vp->v_usecount == 0)
   1172 		vp->v_usecount = 1;
   1173 	else
   1174 		atomic_inc_uint(&vp->v_usecount);
   1175 
   1176 	mutex_exit(vp->v_interlock);
   1177 
   1178 	return error;
   1179 }
   1180 
   1181 /*
   1182  * Try to get an initial reference on this cached vnode.
   1183  * Returns zero on success and  ENOENT if the vnode has been reclaimed.
   1184  * Will wait for the vnode state to be stable.
   1185  *
   1186  * v_interlock locked on entry and unlocked on exit.
   1187  */
   1188 int
   1189 vcache_vget(vnode_t *vp)
   1190 {
   1191 
   1192 	KASSERT(mutex_owned(vp->v_interlock));
   1193 
   1194 	/* Increment hold count to prevent vnode from disappearing. */
   1195 	vp->v_holdcnt++;
   1196 	VSTATE_WAIT_STABLE(vp);
   1197 	vp->v_holdcnt--;
   1198 
   1199 	/* If this was the last reference to a reclaimed vnode free it now. */
   1200 	if (__predict_false(VSTATE_GET(vp) == VS_RECLAIMED)) {
   1201 		if (vp->v_holdcnt == 0 && vp->v_usecount == 0)
   1202 			vcache_free(VNODE_TO_VIMPL(vp));
   1203 		else
   1204 			mutex_exit(vp->v_interlock);
   1205 		return ENOENT;
   1206 	}
   1207 	VSTATE_ASSERT(vp, VS_ACTIVE);
   1208 	if (vp->v_usecount == 0)
   1209 		vp->v_usecount = 1;
   1210 	else
   1211 		atomic_inc_uint(&vp->v_usecount);
   1212 
   1213 	mutex_exit(vp->v_interlock);
   1214 
   1215 	return 0;
   1216 }
   1217 
   1218 /*
   1219  * Get a vnode / fs node pair by key and return it referenced through vpp.
   1220  */
   1221 int
   1222 vcache_get(struct mount *mp, const void *key, size_t key_len,
   1223     struct vnode **vpp)
   1224 {
   1225 	int error;
   1226 	uint32_t hash;
   1227 	const void *new_key;
   1228 	struct vnode *vp;
   1229 	struct vcache_key vcache_key;
   1230 	vnode_impl_t *vip, *new_vip;
   1231 
   1232 	new_key = NULL;
   1233 	*vpp = NULL;
   1234 
   1235 	vcache_key.vk_mount = mp;
   1236 	vcache_key.vk_key = key;
   1237 	vcache_key.vk_key_len = key_len;
   1238 	hash = vcache_hash(&vcache_key);
   1239 
   1240 again:
   1241 	mutex_enter(&vcache_lock);
   1242 	vip = vcache_hash_lookup(&vcache_key, hash);
   1243 
   1244 	/* If found, take a reference or retry. */
   1245 	if (__predict_true(vip != NULL)) {
   1246 		/*
   1247 		 * If the vnode is loading we cannot take the v_interlock
   1248 		 * here as it might change during load (see uvm_obj_setlock()).
   1249 		 * As changing state from VS_LOADING requires both vcache_lock
   1250 		 * and v_interlock it is safe to test with vcache_lock held.
   1251 		 *
   1252 		 * Wait for vnodes changing state from VS_LOADING and retry.
   1253 		 */
   1254 		if (__predict_false(vip->vi_state == VS_LOADING)) {
   1255 			cv_wait(&vcache_cv, &vcache_lock);
   1256 			mutex_exit(&vcache_lock);
   1257 			goto again;
   1258 		}
   1259 		vp = VIMPL_TO_VNODE(vip);
   1260 		mutex_enter(vp->v_interlock);
   1261 		mutex_exit(&vcache_lock);
   1262 		error = vcache_vget(vp);
   1263 		if (error == ENOENT)
   1264 			goto again;
   1265 		if (error == 0)
   1266 			*vpp = vp;
   1267 		KASSERT((error != 0) == (*vpp == NULL));
   1268 		return error;
   1269 	}
   1270 	mutex_exit(&vcache_lock);
   1271 
   1272 	/* Allocate and initialize a new vcache / vnode pair. */
   1273 	error = vfs_busy(mp, NULL);
   1274 	if (error)
   1275 		return error;
   1276 	new_vip = vcache_alloc();
   1277 	new_vip->vi_key = vcache_key;
   1278 	vp = VIMPL_TO_VNODE(new_vip);
   1279 	mutex_enter(&vcache_lock);
   1280 	vip = vcache_hash_lookup(&vcache_key, hash);
   1281 	if (vip == NULL) {
   1282 		SLIST_INSERT_HEAD(&vcache_hashtab[hash & vcache_hashmask],
   1283 		    new_vip, vi_hash);
   1284 		vip = new_vip;
   1285 	}
   1286 
   1287 	/* If another thread beat us inserting this node, retry. */
   1288 	if (vip != new_vip) {
   1289 		vcache_dealloc(new_vip);
   1290 		vfs_unbusy(mp, false, NULL);
   1291 		goto again;
   1292 	}
   1293 	mutex_exit(&vcache_lock);
   1294 
   1295 	/* Load the fs node.  Exclusive as new_node is VS_LOADING. */
   1296 	error = VFS_LOADVNODE(mp, vp, key, key_len, &new_key);
   1297 	if (error) {
   1298 		mutex_enter(&vcache_lock);
   1299 		SLIST_REMOVE(&vcache_hashtab[hash & vcache_hashmask],
   1300 		    new_vip, vnode_impl, vi_hash);
   1301 		vcache_dealloc(new_vip);
   1302 		vfs_unbusy(mp, false, NULL);
   1303 		KASSERT(*vpp == NULL);
   1304 		return error;
   1305 	}
   1306 	KASSERT(new_key != NULL);
   1307 	KASSERT(memcmp(key, new_key, key_len) == 0);
   1308 	KASSERT(vp->v_op != NULL);
   1309 	vfs_insmntque(vp, mp);
   1310 	if ((mp->mnt_iflag & IMNT_MPSAFE) != 0)
   1311 		vp->v_vflag |= VV_MPSAFE;
   1312 	vfs_unbusy(mp, true, NULL);
   1313 
   1314 	/* Finished loading, finalize node. */
   1315 	mutex_enter(&vcache_lock);
   1316 	new_vip->vi_key.vk_key = new_key;
   1317 	mutex_enter(vp->v_interlock);
   1318 	VSTATE_CHANGE(vp, VS_LOADING, VS_ACTIVE);
   1319 	mutex_exit(vp->v_interlock);
   1320 	mutex_exit(&vcache_lock);
   1321 	*vpp = vp;
   1322 	return 0;
   1323 }
   1324 
   1325 /*
   1326  * Create a new vnode / fs node pair and return it referenced through vpp.
   1327  */
   1328 int
   1329 vcache_new(struct mount *mp, struct vnode *dvp, struct vattr *vap,
   1330     kauth_cred_t cred, struct vnode **vpp)
   1331 {
   1332 	int error;
   1333 	uint32_t hash;
   1334 	struct vnode *vp, *ovp;
   1335 	vnode_impl_t *vip, *ovip;
   1336 
   1337 	*vpp = NULL;
   1338 
   1339 	/* Allocate and initialize a new vcache / vnode pair. */
   1340 	error = vfs_busy(mp, NULL);
   1341 	if (error)
   1342 		return error;
   1343 	vip = vcache_alloc();
   1344 	vip->vi_key.vk_mount = mp;
   1345 	vp = VIMPL_TO_VNODE(vip);
   1346 
   1347 	/* Create and load the fs node. */
   1348 	error = VFS_NEWVNODE(mp, dvp, vp, vap, cred,
   1349 	    &vip->vi_key.vk_key_len, &vip->vi_key.vk_key);
   1350 	if (error) {
   1351 		mutex_enter(&vcache_lock);
   1352 		vcache_dealloc(vip);
   1353 		vfs_unbusy(mp, false, NULL);
   1354 		KASSERT(*vpp == NULL);
   1355 		return error;
   1356 	}
   1357 	KASSERT(vip->vi_key.vk_key != NULL);
   1358 	KASSERT(vp->v_op != NULL);
   1359 	hash = vcache_hash(&vip->vi_key);
   1360 
   1361 	/* Wait for previous instance to be reclaimed, then insert new node. */
   1362 	mutex_enter(&vcache_lock);
   1363 	while ((ovip = vcache_hash_lookup(&vip->vi_key, hash))) {
   1364 		ovp = VIMPL_TO_VNODE(ovip);
   1365 		mutex_enter(ovp->v_interlock);
   1366 		mutex_exit(&vcache_lock);
   1367 		error = vcache_vget(ovp);
   1368 		KASSERT(error == ENOENT);
   1369 		mutex_enter(&vcache_lock);
   1370 	}
   1371 	SLIST_INSERT_HEAD(&vcache_hashtab[hash & vcache_hashmask],
   1372 	    vip, vi_hash);
   1373 	mutex_exit(&vcache_lock);
   1374 	vfs_insmntque(vp, mp);
   1375 	if ((mp->mnt_iflag & IMNT_MPSAFE) != 0)
   1376 		vp->v_vflag |= VV_MPSAFE;
   1377 	vfs_unbusy(mp, true, NULL);
   1378 
   1379 	/* Finished loading, finalize node. */
   1380 	mutex_enter(&vcache_lock);
   1381 	mutex_enter(vp->v_interlock);
   1382 	VSTATE_CHANGE(vp, VS_LOADING, VS_ACTIVE);
   1383 	mutex_exit(&vcache_lock);
   1384 	mutex_exit(vp->v_interlock);
   1385 	*vpp = vp;
   1386 	return 0;
   1387 }
   1388 
   1389 /*
   1390  * Prepare key change: update old cache nodes key and lock new cache node.
   1391  * Return an error if the new node already exists.
   1392  */
   1393 int
   1394 vcache_rekey_enter(struct mount *mp, struct vnode *vp,
   1395     const void *old_key, size_t old_key_len,
   1396     const void *new_key, size_t new_key_len)
   1397 {
   1398 	uint32_t old_hash, new_hash;
   1399 	struct vcache_key old_vcache_key, new_vcache_key;
   1400 	vnode_impl_t *vip, *new_vip;
   1401 
   1402 	old_vcache_key.vk_mount = mp;
   1403 	old_vcache_key.vk_key = old_key;
   1404 	old_vcache_key.vk_key_len = old_key_len;
   1405 	old_hash = vcache_hash(&old_vcache_key);
   1406 
   1407 	new_vcache_key.vk_mount = mp;
   1408 	new_vcache_key.vk_key = new_key;
   1409 	new_vcache_key.vk_key_len = new_key_len;
   1410 	new_hash = vcache_hash(&new_vcache_key);
   1411 
   1412 	new_vip = vcache_alloc();
   1413 	new_vip->vi_key = new_vcache_key;
   1414 
   1415 	/* Insert locked new node used as placeholder. */
   1416 	mutex_enter(&vcache_lock);
   1417 	vip = vcache_hash_lookup(&new_vcache_key, new_hash);
   1418 	if (vip != NULL) {
   1419 		vcache_dealloc(new_vip);
   1420 		return EEXIST;
   1421 	}
   1422 	SLIST_INSERT_HEAD(&vcache_hashtab[new_hash & vcache_hashmask],
   1423 	    new_vip, vi_hash);
   1424 
   1425 	/* Replace old nodes key with the temporary copy. */
   1426 	vip = vcache_hash_lookup(&old_vcache_key, old_hash);
   1427 	KASSERT(vip != NULL);
   1428 	KASSERT(VIMPL_TO_VNODE(vip) == vp);
   1429 	KASSERT(vip->vi_key.vk_key != old_vcache_key.vk_key);
   1430 	vip->vi_key = old_vcache_key;
   1431 	mutex_exit(&vcache_lock);
   1432 	return 0;
   1433 }
   1434 
   1435 /*
   1436  * Key change complete: update old node and remove placeholder.
   1437  */
   1438 void
   1439 vcache_rekey_exit(struct mount *mp, struct vnode *vp,
   1440     const void *old_key, size_t old_key_len,
   1441     const void *new_key, size_t new_key_len)
   1442 {
   1443 	uint32_t old_hash, new_hash;
   1444 	struct vcache_key old_vcache_key, new_vcache_key;
   1445 	vnode_impl_t *vip, *new_vip;
   1446 	struct vnode *new_vp;
   1447 
   1448 	old_vcache_key.vk_mount = mp;
   1449 	old_vcache_key.vk_key = old_key;
   1450 	old_vcache_key.vk_key_len = old_key_len;
   1451 	old_hash = vcache_hash(&old_vcache_key);
   1452 
   1453 	new_vcache_key.vk_mount = mp;
   1454 	new_vcache_key.vk_key = new_key;
   1455 	new_vcache_key.vk_key_len = new_key_len;
   1456 	new_hash = vcache_hash(&new_vcache_key);
   1457 
   1458 	mutex_enter(&vcache_lock);
   1459 
   1460 	/* Lookup old and new node. */
   1461 	vip = vcache_hash_lookup(&old_vcache_key, old_hash);
   1462 	KASSERT(vip != NULL);
   1463 	KASSERT(VIMPL_TO_VNODE(vip) == vp);
   1464 
   1465 	new_vip = vcache_hash_lookup(&new_vcache_key, new_hash);
   1466 	KASSERT(new_vip != NULL);
   1467 	KASSERT(new_vip->vi_key.vk_key_len == new_key_len);
   1468 	new_vp = VIMPL_TO_VNODE(new_vip);
   1469 	mutex_enter(new_vp->v_interlock);
   1470 	VSTATE_ASSERT(VIMPL_TO_VNODE(new_vip), VS_LOADING);
   1471 	mutex_exit(new_vp->v_interlock);
   1472 
   1473 	/* Rekey old node and put it onto its new hashlist. */
   1474 	vip->vi_key = new_vcache_key;
   1475 	if (old_hash != new_hash) {
   1476 		SLIST_REMOVE(&vcache_hashtab[old_hash & vcache_hashmask],
   1477 		    vip, vnode_impl, vi_hash);
   1478 		SLIST_INSERT_HEAD(&vcache_hashtab[new_hash & vcache_hashmask],
   1479 		    vip, vi_hash);
   1480 	}
   1481 
   1482 	/* Remove new node used as placeholder. */
   1483 	SLIST_REMOVE(&vcache_hashtab[new_hash & vcache_hashmask],
   1484 	    new_vip, vnode_impl, vi_hash);
   1485 	vcache_dealloc(new_vip);
   1486 }
   1487 
   1488 /*
   1489  * Disassociate the underlying file system from a vnode.
   1490  *
   1491  * Must be called with vnode locked and will return unlocked.
   1492  * Must be called with the interlock held, and will return with it held.
   1493  */
   1494 static void
   1495 vcache_reclaim(vnode_t *vp)
   1496 {
   1497 	lwp_t *l = curlwp;
   1498 	vnode_impl_t *vip = VNODE_TO_VIMPL(vp);
   1499 	struct mount *mp = vp->v_mount;
   1500 	uint32_t hash;
   1501 	uint8_t temp_buf[64], *temp_key;
   1502 	size_t temp_key_len;
   1503 	bool recycle, active;
   1504 	int error;
   1505 
   1506 	KASSERT((vp->v_vflag & VV_LOCKSWORK) == 0 ||
   1507 	    VOP_ISLOCKED(vp) == LK_EXCLUSIVE);
   1508 	KASSERT(mutex_owned(vp->v_interlock));
   1509 	KASSERT(vp->v_usecount != 0);
   1510 
   1511 	active = (vp->v_usecount > 1);
   1512 	temp_key_len = vip->vi_key.vk_key_len;
   1513 	/*
   1514 	 * Prevent the vnode from being recycled or brought into use
   1515 	 * while we clean it out.
   1516 	 */
   1517 	VSTATE_CHANGE(vp, VS_ACTIVE, VS_RECLAIMING);
   1518 	if (vp->v_iflag & VI_EXECMAP) {
   1519 		atomic_add_int(&uvmexp.execpages, -vp->v_uobj.uo_npages);
   1520 		atomic_add_int(&uvmexp.filepages, vp->v_uobj.uo_npages);
   1521 	}
   1522 	vp->v_iflag &= ~(VI_TEXT|VI_EXECMAP);
   1523 	mutex_exit(vp->v_interlock);
   1524 
   1525 	/* Replace the vnode key with a temporary copy. */
   1526 	if (vip->vi_key.vk_key_len > sizeof(temp_buf)) {
   1527 		temp_key = kmem_alloc(temp_key_len, KM_SLEEP);
   1528 	} else {
   1529 		temp_key = temp_buf;
   1530 	}
   1531 	mutex_enter(&vcache_lock);
   1532 	memcpy(temp_key, vip->vi_key.vk_key, temp_key_len);
   1533 	vip->vi_key.vk_key = temp_key;
   1534 	mutex_exit(&vcache_lock);
   1535 
   1536 	fstrans_start(mp, FSTRANS_SHARED);
   1537 
   1538 	/*
   1539 	 * Clean out any cached data associated with the vnode.
   1540 	 * If purging an active vnode, it must be closed and
   1541 	 * deactivated before being reclaimed.
   1542 	 */
   1543 	error = vinvalbuf(vp, V_SAVE, NOCRED, l, 0, 0);
   1544 	if (error != 0) {
   1545 		if (wapbl_vphaswapbl(vp))
   1546 			WAPBL_DISCARD(wapbl_vptomp(vp));
   1547 		error = vinvalbuf(vp, 0, NOCRED, l, 0, 0);
   1548 	}
   1549 	KASSERTMSG((error == 0), "vinvalbuf failed: %d", error);
   1550 	KASSERT((vp->v_iflag & VI_ONWORKLST) == 0);
   1551 	if (active && (vp->v_type == VBLK || vp->v_type == VCHR)) {
   1552 		 spec_node_revoke(vp);
   1553 	}
   1554 
   1555 	/*
   1556 	 * Disassociate the underlying file system from the vnode.
   1557 	 * Note that the VOP_INACTIVE will not unlock the vnode.
   1558 	 */
   1559 	VOP_INACTIVE(vp, &recycle);
   1560 	VOP_UNLOCK(vp);
   1561 	if (VOP_RECLAIM(vp)) {
   1562 		vnpanic(vp, "%s: cannot reclaim", __func__);
   1563 	}
   1564 
   1565 	KASSERT(vp->v_data == NULL);
   1566 	KASSERT(vp->v_uobj.uo_npages == 0);
   1567 
   1568 	if (vp->v_type == VREG && vp->v_ractx != NULL) {
   1569 		uvm_ra_freectx(vp->v_ractx);
   1570 		vp->v_ractx = NULL;
   1571 	}
   1572 
   1573 	/* Purge name cache. */
   1574 	cache_purge(vp);
   1575 
   1576 	/* Remove from vnode cache. */
   1577 	hash = vcache_hash(&vip->vi_key);
   1578 	mutex_enter(&vcache_lock);
   1579 	KASSERT(vip == vcache_hash_lookup(&vip->vi_key, hash));
   1580 	SLIST_REMOVE(&vcache_hashtab[hash & vcache_hashmask],
   1581 	    vip, vnode_impl, vi_hash);
   1582 	mutex_exit(&vcache_lock);
   1583 	if (temp_key != temp_buf)
   1584 		kmem_free(temp_key, temp_key_len);
   1585 
   1586 	/* Done with purge, notify sleepers of the grim news. */
   1587 	mutex_enter(vp->v_interlock);
   1588 	vp->v_op = dead_vnodeop_p;
   1589 	vp->v_vflag |= VV_LOCKSWORK;
   1590 	VSTATE_CHANGE(vp, VS_RECLAIMING, VS_RECLAIMED);
   1591 	vp->v_tag = VT_NON;
   1592 	KNOTE(&vp->v_klist, NOTE_REVOKE);
   1593 	mutex_exit(vp->v_interlock);
   1594 
   1595 	/*
   1596 	 * Move to dead mount.  Must be after changing the operations
   1597 	 * vector as vnode operations enter the mount before using the
   1598 	 * operations vector.  See sys/kern/vnode_if.c.
   1599 	 */
   1600 	vp->v_vflag &= ~VV_ROOT;
   1601 	atomic_inc_uint(&dead_rootmount->mnt_refcnt);
   1602 	vfs_insmntque(vp, dead_rootmount);
   1603 
   1604 	mutex_enter(vp->v_interlock);
   1605 	fstrans_done(mp);
   1606 	KASSERT((vp->v_iflag & VI_ONWORKLST) == 0);
   1607 }
   1608 
   1609 /*
   1610  * Update outstanding I/O count and do wakeup if requested.
   1611  */
   1612 void
   1613 vwakeup(struct buf *bp)
   1614 {
   1615 	vnode_t *vp;
   1616 
   1617 	if ((vp = bp->b_vp) == NULL)
   1618 		return;
   1619 
   1620 	KASSERT(bp->b_objlock == vp->v_interlock);
   1621 	KASSERT(mutex_owned(bp->b_objlock));
   1622 
   1623 	if (--vp->v_numoutput < 0)
   1624 		vnpanic(vp, "%s: neg numoutput, vp %p", __func__, vp);
   1625 	if (vp->v_numoutput == 0)
   1626 		cv_broadcast(&vp->v_cv);
   1627 }
   1628 
   1629 /*
   1630  * Test a vnode for being or becoming dead.  Returns one of:
   1631  * EBUSY:  vnode is becoming dead, with "flags == VDEAD_NOWAIT" only.
   1632  * ENOENT: vnode is dead.
   1633  * 0:      otherwise.
   1634  *
   1635  * Whenever this function returns a non-zero value all future
   1636  * calls will also return a non-zero value.
   1637  */
   1638 int
   1639 vdead_check(struct vnode *vp, int flags)
   1640 {
   1641 
   1642 	KASSERT(mutex_owned(vp->v_interlock));
   1643 
   1644 	if (! ISSET(flags, VDEAD_NOWAIT))
   1645 		VSTATE_WAIT_STABLE(vp);
   1646 
   1647 	if (VSTATE_GET(vp) == VS_RECLAIMING) {
   1648 		KASSERT(ISSET(flags, VDEAD_NOWAIT));
   1649 		return EBUSY;
   1650 	} else if (VSTATE_GET(vp) == VS_RECLAIMED) {
   1651 		return ENOENT;
   1652 	}
   1653 
   1654 	return 0;
   1655 }
   1656 
   1657 int
   1658 vfs_drainvnodes(void)
   1659 {
   1660 	int i, gen;
   1661 
   1662 	mutex_enter(&vdrain_lock);
   1663 	for (i = 0; i < 2; i++) {
   1664 		gen = vdrain_gen;
   1665 		while (gen == vdrain_gen) {
   1666 			cv_broadcast(&vdrain_cv);
   1667 			cv_wait(&vdrain_gen_cv, &vdrain_lock);
   1668 		}
   1669 	}
   1670 	mutex_exit(&vdrain_lock);
   1671 
   1672 	if (numvnodes >= desiredvnodes)
   1673 		return EBUSY;
   1674 
   1675 	if (vcache_hashsize != desiredvnodes)
   1676 		vcache_reinit();
   1677 
   1678 	return 0;
   1679 }
   1680 
   1681 void
   1682 vnpanic(vnode_t *vp, const char *fmt, ...)
   1683 {
   1684 	va_list ap;
   1685 
   1686 #ifdef DIAGNOSTIC
   1687 	vprint(NULL, vp);
   1688 #endif
   1689 	va_start(ap, fmt);
   1690 	vpanic(fmt, ap);
   1691 	va_end(ap);
   1692 }
   1693