Home | History | Annotate | Line # | Download | only in kern
vfs_vnode.c revision 1.57
      1 /*	$NetBSD: vfs_vnode.c,v 1.57 2016/11/03 11:02:09 hannken 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 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.57 2016/11/03 11:02:09 hannken Exp $");
    160 
    161 #define _VFS_VNODE_PRIVATE
    162 
    163 #include <sys/param.h>
    164 #include <sys/kernel.h>
    165 
    166 #include <sys/atomic.h>
    167 #include <sys/buf.h>
    168 #include <sys/conf.h>
    169 #include <sys/device.h>
    170 #include <sys/hash.h>
    171 #include <sys/kauth.h>
    172 #include <sys/kmem.h>
    173 #include <sys/kthread.h>
    174 #include <sys/module.h>
    175 #include <sys/mount.h>
    176 #include <sys/namei.h>
    177 #include <sys/syscallargs.h>
    178 #include <sys/sysctl.h>
    179 #include <sys/systm.h>
    180 #include <sys/vnode.h>
    181 #include <sys/wapbl.h>
    182 #include <sys/fstrans.h>
    183 
    184 #include <uvm/uvm.h>
    185 #include <uvm/uvm_readahead.h>
    186 
    187 /* Flags to vrelel. */
    188 #define	VRELEL_ASYNC_RELE	0x0001	/* Always defer to vrele thread. */
    189 
    190 enum vnode_state {
    191 	VS_MARKER,	/* Stable, used as marker. Will not change. */
    192 	VS_LOADING,	/* Intermediate, initialising the fs node. */
    193 	VS_ACTIVE,	/* Stable, valid fs node attached. */
    194 	VS_BLOCKED,	/* Intermediate, active, no new references allowed. */
    195 	VS_RECLAIMING,	/* Intermediate, detaching the fs node. */
    196 	VS_RECLAIMED	/* Stable, no fs node attached. */
    197 };
    198 struct vcache_key {
    199 	struct mount *vk_mount;
    200 	const void *vk_key;
    201 	size_t vk_key_len;
    202 };
    203 struct vnode_impl {
    204 	struct vnode vi_vnode;
    205 	enum vnode_state vi_state;
    206 	SLIST_ENTRY(vnode_impl) vi_hash;
    207 	struct vcache_key vi_key;
    208 };
    209 typedef struct vnode_impl vnode_impl_t;
    210 
    211 #define VIMPL_TO_VNODE(node)	((vnode_t *)(node))
    212 #define VNODE_TO_VIMPL(vp)	((vnode_impl_t *)(vp))
    213 
    214 u_int			numvnodes		__cacheline_aligned;
    215 
    216 /*
    217  * There are two free lists: one is for vnodes which have no buffer/page
    218  * references and one for those which do (i.e. v_holdcnt is non-zero).
    219  * Vnode recycling mechanism first attempts to look into the former list.
    220  */
    221 static kmutex_t		vnode_free_list_lock	__cacheline_aligned;
    222 static vnodelst_t	vnode_free_list		__cacheline_aligned;
    223 static vnodelst_t	vnode_hold_list		__cacheline_aligned;
    224 static kcondvar_t	vdrain_cv		__cacheline_aligned;
    225 
    226 static vnodelst_t	vrele_list		__cacheline_aligned;
    227 static kmutex_t		vrele_lock		__cacheline_aligned;
    228 static kcondvar_t	vrele_cv		__cacheline_aligned;
    229 static lwp_t *		vrele_lwp		__cacheline_aligned;
    230 static int		vrele_pending		__cacheline_aligned;
    231 static int		vrele_gen		__cacheline_aligned;
    232 
    233 SLIST_HEAD(hashhead, vnode_impl);
    234 static struct {
    235 	kmutex_t	lock;
    236 	kcondvar_t	cv;
    237 	u_long		hashmask;
    238 	struct hashhead	*hashtab;
    239 	pool_cache_t	pool;
    240 }			vcache			__cacheline_aligned;
    241 
    242 static int		cleanvnode(void);
    243 static vnode_impl_t *vcache_alloc(void);
    244 static void		vcache_free(vnode_impl_t *);
    245 static void		vcache_init(void);
    246 static void		vcache_reinit(void);
    247 static void		vcache_reclaim(vnode_t *);
    248 static void		vrelel(vnode_t *, int);
    249 static void		vdrain_thread(void *);
    250 static void		vrele_thread(void *);
    251 static void		vnpanic(vnode_t *, const char *, ...)
    252     __printflike(2, 3);
    253 
    254 /* Routines having to do with the management of the vnode table. */
    255 extern struct mount	*dead_rootmount;
    256 extern int		(**dead_vnodeop_p)(void *);
    257 extern struct vfsops	dead_vfsops;
    258 
    259 /* Vnode state operations and diagnostics. */
    260 
    261 static const char *
    262 vstate_name(enum vnode_state state)
    263 {
    264 
    265 	switch (state) {
    266 	case VS_MARKER:
    267 		return "MARKER";
    268 	case VS_LOADING:
    269 		return "LOADING";
    270 	case VS_ACTIVE:
    271 		return "ACTIVE";
    272 	case VS_BLOCKED:
    273 		return "BLOCKED";
    274 	case VS_RECLAIMING:
    275 		return "RECLAIMING";
    276 	case VS_RECLAIMED:
    277 		return "RECLAIMED";
    278 	default:
    279 		return "ILLEGAL";
    280 	}
    281 }
    282 
    283 #if defined(DIAGNOSTIC)
    284 
    285 #define VSTATE_GET(vp) \
    286 	vstate_assert_get((vp), __func__, __LINE__)
    287 #define VSTATE_CHANGE(vp, from, to) \
    288 	vstate_assert_change((vp), (from), (to), __func__, __LINE__)
    289 #define VSTATE_WAIT_STABLE(vp) \
    290 	vstate_assert_wait_stable((vp), __func__, __LINE__)
    291 #define VSTATE_ASSERT(vp, state) \
    292 	vstate_assert((vp), (state), __func__, __LINE__)
    293 
    294 static void
    295 vstate_assert(vnode_t *vp, enum vnode_state state, const char *func, int line)
    296 {
    297 	vnode_impl_t *node = VNODE_TO_VIMPL(vp);
    298 
    299 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    300 
    301 	if (__predict_true(node->vi_state == state))
    302 		return;
    303 	vnpanic(vp, "state is %s, expected %s at %s:%d",
    304 	    vstate_name(node->vi_state), vstate_name(state), func, line);
    305 }
    306 
    307 static enum vnode_state
    308 vstate_assert_get(vnode_t *vp, const char *func, int line)
    309 {
    310 	vnode_impl_t *node = VNODE_TO_VIMPL(vp);
    311 
    312 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    313 	if (node->vi_state == VS_MARKER)
    314 		vnpanic(vp, "state is %s at %s:%d",
    315 		    vstate_name(node->vi_state), func, line);
    316 
    317 	return node->vi_state;
    318 }
    319 
    320 static void
    321 vstate_assert_wait_stable(vnode_t *vp, const char *func, int line)
    322 {
    323 	vnode_impl_t *node = VNODE_TO_VIMPL(vp);
    324 
    325 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    326 	if (node->vi_state == VS_MARKER)
    327 		vnpanic(vp, "state is %s at %s:%d",
    328 		    vstate_name(node->vi_state), func, line);
    329 
    330 	while (node->vi_state != VS_ACTIVE && node->vi_state != VS_RECLAIMED)
    331 		cv_wait(&vp->v_cv, vp->v_interlock);
    332 
    333 	if (node->vi_state == VS_MARKER)
    334 		vnpanic(vp, "state is %s at %s:%d",
    335 		    vstate_name(node->vi_state), func, line);
    336 }
    337 
    338 static void
    339 vstate_assert_change(vnode_t *vp, enum vnode_state from, enum vnode_state to,
    340     const char *func, int line)
    341 {
    342 	vnode_impl_t *node = VNODE_TO_VIMPL(vp);
    343 
    344 	KASSERTMSG(mutex_owned(vp->v_interlock), "at %s:%d", func, line);
    345 	if (from == VS_LOADING)
    346 		KASSERTMSG(mutex_owned(&vcache.lock), "at %s:%d", func, line);
    347 
    348 	if (from == VS_MARKER)
    349 		vnpanic(vp, "from is %s at %s:%d",
    350 		    vstate_name(from), func, line);
    351 	if (to == VS_MARKER)
    352 		vnpanic(vp, "to is %s at %s:%d",
    353 		    vstate_name(to), func, line);
    354 	if (node->vi_state != from)
    355 		vnpanic(vp, "from is %s, expected %s at %s:%d\n",
    356 		    vstate_name(node->vi_state), vstate_name(from), func, line);
    357 
    358 	node->vi_state = to;
    359 	if (from == VS_LOADING)
    360 		cv_broadcast(&vcache.cv);
    361 	if (to == VS_ACTIVE || to == VS_RECLAIMED)
    362 		cv_broadcast(&vp->v_cv);
    363 }
    364 
    365 #else /* defined(DIAGNOSTIC) */
    366 
    367 #define VSTATE_GET(vp) \
    368 	(VNODE_TO_VIMPL((vp))->vi_state)
    369 #define VSTATE_CHANGE(vp, from, to) \
    370 	vstate_change((vp), (from), (to))
    371 #define VSTATE_WAIT_STABLE(vp) \
    372 	vstate_wait_stable((vp))
    373 #define VSTATE_ASSERT(vp, state)
    374 
    375 static void
    376 vstate_wait_stable(vnode_t *vp)
    377 {
    378 	vnode_impl_t *node = VNODE_TO_VIMPL(vp);
    379 
    380 	while (node->vi_state != VS_ACTIVE && node->vi_state != VS_RECLAIMED)
    381 		cv_wait(&vp->v_cv, vp->v_interlock);
    382 }
    383 
    384 static void
    385 vstate_change(vnode_t *vp, enum vnode_state from, enum vnode_state to)
    386 {
    387 	vnode_impl_t *node = VNODE_TO_VIMPL(vp);
    388 
    389 	node->vi_state = to;
    390 	if (from == VS_LOADING)
    391 		cv_broadcast(&vcache.cv);
    392 	if (to == VS_ACTIVE || to == VS_RECLAIMED)
    393 		cv_broadcast(&vp->v_cv);
    394 }
    395 
    396 #endif /* defined(DIAGNOSTIC) */
    397 
    398 void
    399 vfs_vnode_sysinit(void)
    400 {
    401 	int error __diagused;
    402 
    403 	dead_rootmount = vfs_mountalloc(&dead_vfsops, NULL);
    404 	KASSERT(dead_rootmount != NULL);
    405 	dead_rootmount->mnt_iflag = IMNT_MPSAFE;
    406 
    407 	mutex_init(&vnode_free_list_lock, MUTEX_DEFAULT, IPL_NONE);
    408 	TAILQ_INIT(&vnode_free_list);
    409 	TAILQ_INIT(&vnode_hold_list);
    410 	TAILQ_INIT(&vrele_list);
    411 
    412 	vcache_init();
    413 
    414 	mutex_init(&vrele_lock, MUTEX_DEFAULT, IPL_NONE);
    415 	cv_init(&vdrain_cv, "vdrain");
    416 	cv_init(&vrele_cv, "vrele");
    417 	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, vdrain_thread,
    418 	    NULL, NULL, "vdrain");
    419 	KASSERTMSG((error == 0), "kthread_create(vdrain) failed: %d", error);
    420 	error = kthread_create(PRI_VM, KTHREAD_MPSAFE, NULL, vrele_thread,
    421 	    NULL, &vrele_lwp, "vrele");
    422 	KASSERTMSG((error == 0), "kthread_create(vrele) failed: %d", error);
    423 }
    424 
    425 /*
    426  * Allocate a new marker vnode.
    427  */
    428 vnode_t *
    429 vnalloc_marker(struct mount *mp)
    430 {
    431 	vnode_impl_t *node;
    432 	vnode_t *vp;
    433 
    434 	node = pool_cache_get(vcache.pool, PR_WAITOK);
    435 	memset(node, 0, sizeof(*node));
    436 	vp = VIMPL_TO_VNODE(node);
    437 	uvm_obj_init(&vp->v_uobj, &uvm_vnodeops, true, 0);
    438 	vp->v_mount = mp;
    439 	vp->v_type = VBAD;
    440 	node->vi_state = VS_MARKER;
    441 
    442 	return vp;
    443 }
    444 
    445 /*
    446  * Free a marker vnode.
    447  */
    448 void
    449 vnfree_marker(vnode_t *vp)
    450 {
    451 	vnode_impl_t *node;
    452 
    453 	node = VNODE_TO_VIMPL(vp);
    454 	KASSERT(node->vi_state == VS_MARKER);
    455 	uvm_obj_destroy(&vp->v_uobj, true);
    456 	pool_cache_put(vcache.pool, node);
    457 }
    458 
    459 /*
    460  * Test a vnode for being a marker vnode.
    461  */
    462 bool
    463 vnis_marker(vnode_t *vp)
    464 {
    465 
    466 	return (VNODE_TO_VIMPL(vp)->vi_state == VS_MARKER);
    467 }
    468 
    469 /*
    470  * cleanvnode: grab a vnode from freelist, clean and free it.
    471  *
    472  * => Releases vnode_free_list_lock.
    473  */
    474 static int
    475 cleanvnode(void)
    476 {
    477 	vnode_t *vp;
    478 	vnodelst_t *listhd;
    479 	struct mount *mp;
    480 
    481 	KASSERT(mutex_owned(&vnode_free_list_lock));
    482 
    483 	listhd = &vnode_free_list;
    484 try_nextlist:
    485 	TAILQ_FOREACH(vp, listhd, v_freelist) {
    486 		/*
    487 		 * It's safe to test v_usecount and v_iflag
    488 		 * without holding the interlock here, since
    489 		 * these vnodes should never appear on the
    490 		 * lists.
    491 		 */
    492 		KASSERT(vp->v_usecount == 0);
    493 		KASSERT(vp->v_freelisthd == listhd);
    494 
    495 		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
    496 			continue;
    497 		if (!mutex_tryenter(vp->v_interlock)) {
    498 			VOP_UNLOCK(vp);
    499 			continue;
    500 		}
    501 		mp = vp->v_mount;
    502 		if (fstrans_start_nowait(mp, FSTRANS_SHARED) != 0) {
    503 			mutex_exit(vp->v_interlock);
    504 			VOP_UNLOCK(vp);
    505 			continue;
    506 		}
    507 		break;
    508 	}
    509 
    510 	if (vp == NULL) {
    511 		if (listhd == &vnode_free_list) {
    512 			listhd = &vnode_hold_list;
    513 			goto try_nextlist;
    514 		}
    515 		mutex_exit(&vnode_free_list_lock);
    516 		return EBUSY;
    517 	}
    518 
    519 	/* Remove it from the freelist. */
    520 	TAILQ_REMOVE(listhd, vp, v_freelist);
    521 	vp->v_freelisthd = NULL;
    522 	mutex_exit(&vnode_free_list_lock);
    523 
    524 	KASSERT(vp->v_usecount == 0);
    525 
    526 	/*
    527 	 * The vnode is still associated with a file system, so we must
    528 	 * clean it out before freeing it.  We need to add a reference
    529 	 * before doing this.
    530 	 */
    531 	vp->v_usecount = 1;
    532 	vcache_reclaim(vp);
    533 	vrelel(vp, 0);
    534 	fstrans_done(mp);
    535 
    536 	return 0;
    537 }
    538 
    539 /*
    540  * Helper thread to keep the number of vnodes below desiredvnodes.
    541  */
    542 static void
    543 vdrain_thread(void *cookie)
    544 {
    545 	int error;
    546 
    547 	mutex_enter(&vnode_free_list_lock);
    548 
    549 	for (;;) {
    550 		cv_timedwait(&vdrain_cv, &vnode_free_list_lock, hz);
    551 		while (numvnodes > desiredvnodes) {
    552 			error = cleanvnode();
    553 			if (error)
    554 				kpause("vndsbusy", false, hz, NULL);
    555 			mutex_enter(&vnode_free_list_lock);
    556 			if (error)
    557 				break;
    558 		}
    559 	}
    560 }
    561 
    562 /*
    563  * Remove a vnode from its freelist.
    564  */
    565 void
    566 vremfree(vnode_t *vp)
    567 {
    568 
    569 	KASSERT(mutex_owned(vp->v_interlock));
    570 	KASSERT(vp->v_usecount == 0);
    571 
    572 	/*
    573 	 * Note that the reference count must not change until
    574 	 * the vnode is removed.
    575 	 */
    576 	mutex_enter(&vnode_free_list_lock);
    577 	if (vp->v_holdcnt > 0) {
    578 		KASSERT(vp->v_freelisthd == &vnode_hold_list);
    579 	} else {
    580 		KASSERT(vp->v_freelisthd == &vnode_free_list);
    581 	}
    582 	TAILQ_REMOVE(vp->v_freelisthd, vp, v_freelist);
    583 	vp->v_freelisthd = NULL;
    584 	mutex_exit(&vnode_free_list_lock);
    585 }
    586 
    587 /*
    588  * vget: get a particular vnode from the free list, increment its reference
    589  * count and return it.
    590  *
    591  * => Must be called with v_interlock held.
    592  *
    593  * If state is VS_RECLAIMING, the vnode may be eliminated in vcache_reclaim().
    594  * In that case, we cannot grab the vnode, so the process is awakened when
    595  * the transition is completed, and an error returned to indicate that the
    596  * vnode is no longer usable.
    597  *
    598  * If state is VS_LOADING or VS_BLOCKED, wait until the vnode enters a
    599  * stable state (VS_ACTIVE or VS_RECLAIMED).
    600  */
    601 int
    602 vget(vnode_t *vp, int flags, bool waitok)
    603 {
    604 
    605 	KASSERT(mutex_owned(vp->v_interlock));
    606 	KASSERT((flags & ~LK_NOWAIT) == 0);
    607 	KASSERT(waitok == ((flags & LK_NOWAIT) == 0));
    608 
    609 	/*
    610 	 * Before adding a reference, we must remove the vnode
    611 	 * from its freelist.
    612 	 */
    613 	if (vp->v_usecount == 0) {
    614 		vremfree(vp);
    615 		vp->v_usecount = 1;
    616 	} else {
    617 		atomic_inc_uint(&vp->v_usecount);
    618 	}
    619 
    620 	/*
    621 	 * If the vnode is in the process of changing state we wait
    622 	 * for the change to complete and take care not to return
    623 	 * a clean vnode.
    624 	 */
    625 	if (! ISSET(flags, LK_NOWAIT))
    626 		VSTATE_WAIT_STABLE(vp);
    627 	if (VSTATE_GET(vp) == VS_RECLAIMED) {
    628 		vrelel(vp, 0);
    629 		return ENOENT;
    630 	} else if (VSTATE_GET(vp) != VS_ACTIVE) {
    631 		KASSERT(ISSET(flags, LK_NOWAIT));
    632 		vrelel(vp, 0);
    633 		return EBUSY;
    634 	}
    635 
    636 	/*
    637 	 * Ok, we got it in good shape.
    638 	 */
    639 	VSTATE_ASSERT(vp, VS_ACTIVE);
    640 	mutex_exit(vp->v_interlock);
    641 
    642 	return 0;
    643 }
    644 
    645 /*
    646  * vput: unlock and release the reference.
    647  */
    648 void
    649 vput(vnode_t *vp)
    650 {
    651 
    652 	VOP_UNLOCK(vp);
    653 	vrele(vp);
    654 }
    655 
    656 /*
    657  * Try to drop reference on a vnode.  Abort if we are releasing the
    658  * last reference.  Note: this _must_ succeed if not the last reference.
    659  */
    660 static inline bool
    661 vtryrele(vnode_t *vp)
    662 {
    663 	u_int use, next;
    664 
    665 	for (use = vp->v_usecount;; use = next) {
    666 		if (use == 1) {
    667 			return false;
    668 		}
    669 		KASSERT(use > 1);
    670 		next = atomic_cas_uint(&vp->v_usecount, use, use - 1);
    671 		if (__predict_true(next == use)) {
    672 			return true;
    673 		}
    674 	}
    675 }
    676 
    677 /*
    678  * Vnode release.  If reference count drops to zero, call inactive
    679  * routine and either return to freelist or free to the pool.
    680  */
    681 static void
    682 vrelel(vnode_t *vp, int flags)
    683 {
    684 	bool recycle, defer;
    685 	int error;
    686 
    687 	KASSERT(mutex_owned(vp->v_interlock));
    688 	KASSERT(vp->v_freelisthd == NULL);
    689 
    690 	if (__predict_false(vp->v_op == dead_vnodeop_p &&
    691 	    VSTATE_GET(vp) != VS_RECLAIMED)) {
    692 		vnpanic(vp, "dead but not clean");
    693 	}
    694 
    695 	/*
    696 	 * If not the last reference, just drop the reference count
    697 	 * and unlock.
    698 	 */
    699 	if (vtryrele(vp)) {
    700 		mutex_exit(vp->v_interlock);
    701 		return;
    702 	}
    703 	if (vp->v_usecount <= 0 || vp->v_writecount != 0) {
    704 		vnpanic(vp, "%s: bad ref count", __func__);
    705 	}
    706 
    707 #ifdef DIAGNOSTIC
    708 	if ((vp->v_type == VBLK || vp->v_type == VCHR) &&
    709 	    vp->v_specnode != NULL && vp->v_specnode->sn_opencnt != 0) {
    710 		vprint("vrelel: missing VOP_CLOSE()", vp);
    711 	}
    712 #endif
    713 
    714 	/*
    715 	 * If not clean, deactivate the vnode, but preserve
    716 	 * our reference across the call to VOP_INACTIVE().
    717 	 */
    718 	if (VSTATE_GET(vp) != VS_RECLAIMED) {
    719 		recycle = false;
    720 
    721 		/*
    722 		 * XXX This ugly block can be largely eliminated if
    723 		 * locking is pushed down into the file systems.
    724 		 *
    725 		 * Defer vnode release to vrele_thread if caller
    726 		 * requests it explicitly or is the pagedaemon.
    727 		 */
    728 		if ((curlwp == uvm.pagedaemon_lwp) ||
    729 		    (flags & VRELEL_ASYNC_RELE) != 0) {
    730 			defer = true;
    731 		} else if (curlwp == vrele_lwp) {
    732 			/*
    733 			 * We have to try harder.
    734 			 */
    735 			mutex_exit(vp->v_interlock);
    736 			error = vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
    737 			KASSERTMSG((error == 0), "vn_lock failed: %d", error);
    738 			mutex_enter(vp->v_interlock);
    739 			defer = false;
    740 		} else {
    741 			/* If we can't acquire the lock, then defer. */
    742 			mutex_exit(vp->v_interlock);
    743 			error = vn_lock(vp,
    744 			    LK_EXCLUSIVE | LK_RETRY | LK_NOWAIT);
    745 			defer = (error != 0);
    746 			mutex_enter(vp->v_interlock);
    747 		}
    748 
    749 		KASSERT(mutex_owned(vp->v_interlock));
    750 		KASSERT(! (curlwp == vrele_lwp && defer));
    751 
    752 		if (defer) {
    753 			/*
    754 			 * Defer reclaim to the kthread; it's not safe to
    755 			 * clean it here.  We donate it our last reference.
    756 			 */
    757 			mutex_enter(&vrele_lock);
    758 			TAILQ_INSERT_TAIL(&vrele_list, vp, v_freelist);
    759 			if (++vrele_pending > (desiredvnodes >> 8))
    760 				cv_signal(&vrele_cv);
    761 			mutex_exit(&vrele_lock);
    762 			mutex_exit(vp->v_interlock);
    763 			return;
    764 		}
    765 
    766 		/*
    767 		 * If the node got another reference while we
    768 		 * released the interlock, don't try to inactivate it yet.
    769 		 */
    770 		if (__predict_false(vtryrele(vp))) {
    771 			VOP_UNLOCK(vp);
    772 			mutex_exit(vp->v_interlock);
    773 			return;
    774 		}
    775 		VSTATE_CHANGE(vp, VS_ACTIVE, VS_BLOCKED);
    776 		mutex_exit(vp->v_interlock);
    777 
    778 		/*
    779 		 * The vnode must not gain another reference while being
    780 		 * deactivated.  If VOP_INACTIVE() indicates that
    781 		 * the described file has been deleted, then recycle
    782 		 * the vnode.
    783 		 *
    784 		 * Note that VOP_INACTIVE() will drop the vnode lock.
    785 		 */
    786 		VOP_INACTIVE(vp, &recycle);
    787 		if (recycle) {
    788 			/* vcache_reclaim() below will drop the lock. */
    789 			if (vn_lock(vp, LK_EXCLUSIVE) != 0)
    790 				recycle = false;
    791 		}
    792 		mutex_enter(vp->v_interlock);
    793 		VSTATE_CHANGE(vp, VS_BLOCKED, VS_ACTIVE);
    794 		if (!recycle) {
    795 			if (vtryrele(vp)) {
    796 				mutex_exit(vp->v_interlock);
    797 				return;
    798 			}
    799 		}
    800 
    801 		/* Take care of space accounting. */
    802 		if (vp->v_iflag & VI_EXECMAP) {
    803 			atomic_add_int(&uvmexp.execpages,
    804 			    -vp->v_uobj.uo_npages);
    805 			atomic_add_int(&uvmexp.filepages,
    806 			    vp->v_uobj.uo_npages);
    807 		}
    808 		vp->v_iflag &= ~(VI_TEXT|VI_EXECMAP|VI_WRMAP);
    809 		vp->v_vflag &= ~VV_MAPPED;
    810 
    811 		/*
    812 		 * Recycle the vnode if the file is now unused (unlinked),
    813 		 * otherwise just free it.
    814 		 */
    815 		if (recycle) {
    816 			VSTATE_ASSERT(vp, VS_ACTIVE);
    817 			vcache_reclaim(vp);
    818 		}
    819 		KASSERT(vp->v_usecount > 0);
    820 	}
    821 
    822 	if (atomic_dec_uint_nv(&vp->v_usecount) != 0) {
    823 		/* Gained another reference while being reclaimed. */
    824 		mutex_exit(vp->v_interlock);
    825 		return;
    826 	}
    827 
    828 	if (VSTATE_GET(vp) == VS_RECLAIMED) {
    829 		/*
    830 		 * It's clean so destroy it.  It isn't referenced
    831 		 * anywhere since it has been reclaimed.
    832 		 */
    833 		KASSERT(vp->v_holdcnt == 0);
    834 		KASSERT(vp->v_writecount == 0);
    835 		mutex_exit(vp->v_interlock);
    836 		vfs_insmntque(vp, NULL);
    837 		if (vp->v_type == VBLK || vp->v_type == VCHR) {
    838 			spec_node_destroy(vp);
    839 		}
    840 		vcache_free(VNODE_TO_VIMPL(vp));
    841 	} else {
    842 		/*
    843 		 * Otherwise, put it back onto the freelist.  It
    844 		 * can't be destroyed while still associated with
    845 		 * a file system.
    846 		 */
    847 		mutex_enter(&vnode_free_list_lock);
    848 		if (vp->v_holdcnt > 0) {
    849 			vp->v_freelisthd = &vnode_hold_list;
    850 		} else {
    851 			vp->v_freelisthd = &vnode_free_list;
    852 		}
    853 		TAILQ_INSERT_TAIL(vp->v_freelisthd, vp, v_freelist);
    854 		mutex_exit(&vnode_free_list_lock);
    855 		mutex_exit(vp->v_interlock);
    856 	}
    857 }
    858 
    859 void
    860 vrele(vnode_t *vp)
    861 {
    862 
    863 	if (vtryrele(vp)) {
    864 		return;
    865 	}
    866 	mutex_enter(vp->v_interlock);
    867 	vrelel(vp, 0);
    868 }
    869 
    870 /*
    871  * Asynchronous vnode release, vnode is released in different context.
    872  */
    873 void
    874 vrele_async(vnode_t *vp)
    875 {
    876 
    877 	if (vtryrele(vp)) {
    878 		return;
    879 	}
    880 	mutex_enter(vp->v_interlock);
    881 	vrelel(vp, VRELEL_ASYNC_RELE);
    882 }
    883 
    884 static void
    885 vrele_thread(void *cookie)
    886 {
    887 	vnodelst_t skip_list;
    888 	vnode_t *vp;
    889 	struct mount *mp;
    890 
    891 	TAILQ_INIT(&skip_list);
    892 
    893 	mutex_enter(&vrele_lock);
    894 	for (;;) {
    895 		while (TAILQ_EMPTY(&vrele_list)) {
    896 			vrele_gen++;
    897 			cv_broadcast(&vrele_cv);
    898 			cv_timedwait(&vrele_cv, &vrele_lock, hz);
    899 			TAILQ_CONCAT(&vrele_list, &skip_list, v_freelist);
    900 		}
    901 		vp = TAILQ_FIRST(&vrele_list);
    902 		mp = vp->v_mount;
    903 		TAILQ_REMOVE(&vrele_list, vp, v_freelist);
    904 		if (fstrans_start_nowait(mp, FSTRANS_LAZY) != 0) {
    905 			TAILQ_INSERT_TAIL(&skip_list, vp, v_freelist);
    906 			continue;
    907 		}
    908 		vrele_pending--;
    909 		mutex_exit(&vrele_lock);
    910 
    911 		/*
    912 		 * If not the last reference, then ignore the vnode
    913 		 * and look for more work.
    914 		 */
    915 		mutex_enter(vp->v_interlock);
    916 		vrelel(vp, 0);
    917 		fstrans_done(mp);
    918 		mutex_enter(&vrele_lock);
    919 	}
    920 }
    921 
    922 void
    923 vrele_flush(void)
    924 {
    925 	int gen;
    926 
    927 	mutex_enter(&vrele_lock);
    928 	gen = vrele_gen;
    929 	while (vrele_pending && gen == vrele_gen) {
    930 		cv_broadcast(&vrele_cv);
    931 		cv_wait(&vrele_cv, &vrele_lock);
    932 	}
    933 	mutex_exit(&vrele_lock);
    934 }
    935 
    936 /*
    937  * Vnode reference, where a reference is already held by some other
    938  * object (for example, a file structure).
    939  */
    940 void
    941 vref(vnode_t *vp)
    942 {
    943 
    944 	KASSERT(vp->v_usecount != 0);
    945 
    946 	atomic_inc_uint(&vp->v_usecount);
    947 }
    948 
    949 /*
    950  * Page or buffer structure gets a reference.
    951  * Called with v_interlock held.
    952  */
    953 void
    954 vholdl(vnode_t *vp)
    955 {
    956 
    957 	KASSERT(mutex_owned(vp->v_interlock));
    958 
    959 	if (vp->v_holdcnt++ == 0 && vp->v_usecount == 0) {
    960 		mutex_enter(&vnode_free_list_lock);
    961 		KASSERT(vp->v_freelisthd == &vnode_free_list);
    962 		TAILQ_REMOVE(vp->v_freelisthd, vp, v_freelist);
    963 		vp->v_freelisthd = &vnode_hold_list;
    964 		TAILQ_INSERT_TAIL(vp->v_freelisthd, vp, v_freelist);
    965 		mutex_exit(&vnode_free_list_lock);
    966 	}
    967 }
    968 
    969 /*
    970  * Page or buffer structure frees a reference.
    971  * Called with v_interlock held.
    972  */
    973 void
    974 holdrelel(vnode_t *vp)
    975 {
    976 
    977 	KASSERT(mutex_owned(vp->v_interlock));
    978 
    979 	if (vp->v_holdcnt <= 0) {
    980 		vnpanic(vp, "%s: holdcnt vp %p", __func__, vp);
    981 	}
    982 
    983 	vp->v_holdcnt--;
    984 	if (vp->v_holdcnt == 0 && vp->v_usecount == 0) {
    985 		mutex_enter(&vnode_free_list_lock);
    986 		KASSERT(vp->v_freelisthd == &vnode_hold_list);
    987 		TAILQ_REMOVE(vp->v_freelisthd, vp, v_freelist);
    988 		vp->v_freelisthd = &vnode_free_list;
    989 		TAILQ_INSERT_TAIL(vp->v_freelisthd, vp, v_freelist);
    990 		mutex_exit(&vnode_free_list_lock);
    991 	}
    992 }
    993 
    994 /*
    995  * Recycle an unused vnode if caller holds the last reference.
    996  */
    997 bool
    998 vrecycle(vnode_t *vp)
    999 {
   1000 
   1001 	if (vn_lock(vp, LK_EXCLUSIVE) != 0)
   1002 		return false;
   1003 
   1004 	mutex_enter(vp->v_interlock);
   1005 
   1006 	if (vp->v_usecount != 1) {
   1007 		mutex_exit(vp->v_interlock);
   1008 		VOP_UNLOCK(vp);
   1009 		return false;
   1010 	}
   1011 	vcache_reclaim(vp);
   1012 	vrelel(vp, 0);
   1013 	return true;
   1014 }
   1015 
   1016 /*
   1017  * Eliminate all activity associated with the requested vnode
   1018  * and with all vnodes aliased to the requested vnode.
   1019  */
   1020 void
   1021 vrevoke(vnode_t *vp)
   1022 {
   1023 	vnode_t *vq;
   1024 	enum vtype type;
   1025 	dev_t dev;
   1026 
   1027 	KASSERT(vp->v_usecount > 0);
   1028 
   1029 	mutex_enter(vp->v_interlock);
   1030 	VSTATE_WAIT_STABLE(vp);
   1031 	if (VSTATE_GET(vp) == VS_RECLAIMED) {
   1032 		mutex_exit(vp->v_interlock);
   1033 		return;
   1034 	} else if (vp->v_type != VBLK && vp->v_type != VCHR) {
   1035 		atomic_inc_uint(&vp->v_usecount);
   1036 		mutex_exit(vp->v_interlock);
   1037 		vgone(vp);
   1038 		return;
   1039 	} else {
   1040 		dev = vp->v_rdev;
   1041 		type = vp->v_type;
   1042 		mutex_exit(vp->v_interlock);
   1043 	}
   1044 
   1045 	while (spec_node_lookup_by_dev(type, dev, &vq) == 0) {
   1046 		vgone(vq);
   1047 	}
   1048 }
   1049 
   1050 /*
   1051  * Eliminate all activity associated with a vnode in preparation for
   1052  * reuse.  Drops a reference from the vnode.
   1053  */
   1054 void
   1055 vgone(vnode_t *vp)
   1056 {
   1057 
   1058 	if (vn_lock(vp, LK_EXCLUSIVE) != 0) {
   1059 		VSTATE_ASSERT(vp, VS_RECLAIMED);
   1060 		vrele(vp);
   1061 	}
   1062 
   1063 	mutex_enter(vp->v_interlock);
   1064 	vcache_reclaim(vp);
   1065 	vrelel(vp, 0);
   1066 }
   1067 
   1068 static inline uint32_t
   1069 vcache_hash(const struct vcache_key *key)
   1070 {
   1071 	uint32_t hash = HASH32_BUF_INIT;
   1072 
   1073 	hash = hash32_buf(&key->vk_mount, sizeof(struct mount *), hash);
   1074 	hash = hash32_buf(key->vk_key, key->vk_key_len, hash);
   1075 	return hash;
   1076 }
   1077 
   1078 static void
   1079 vcache_init(void)
   1080 {
   1081 
   1082 	vcache.pool = pool_cache_init(sizeof(vnode_impl_t), 0, 0, 0,
   1083 	    "vcachepl", NULL, IPL_NONE, NULL, NULL, NULL);
   1084 	KASSERT(vcache.pool != NULL);
   1085 	mutex_init(&vcache.lock, MUTEX_DEFAULT, IPL_NONE);
   1086 	cv_init(&vcache.cv, "vcache");
   1087 	vcache.hashtab = hashinit(desiredvnodes, HASH_SLIST, true,
   1088 	    &vcache.hashmask);
   1089 }
   1090 
   1091 static void
   1092 vcache_reinit(void)
   1093 {
   1094 	int i;
   1095 	uint32_t hash;
   1096 	u_long oldmask, newmask;
   1097 	struct hashhead *oldtab, *newtab;
   1098 	vnode_impl_t *node;
   1099 
   1100 	newtab = hashinit(desiredvnodes, HASH_SLIST, true, &newmask);
   1101 	mutex_enter(&vcache.lock);
   1102 	oldtab = vcache.hashtab;
   1103 	oldmask = vcache.hashmask;
   1104 	vcache.hashtab = newtab;
   1105 	vcache.hashmask = newmask;
   1106 	for (i = 0; i <= oldmask; i++) {
   1107 		while ((node = SLIST_FIRST(&oldtab[i])) != NULL) {
   1108 			SLIST_REMOVE(&oldtab[i], node, vnode_impl, vi_hash);
   1109 			hash = vcache_hash(&node->vi_key);
   1110 			SLIST_INSERT_HEAD(&newtab[hash & vcache.hashmask],
   1111 			    node, vi_hash);
   1112 		}
   1113 	}
   1114 	mutex_exit(&vcache.lock);
   1115 	hashdone(oldtab, HASH_SLIST, oldmask);
   1116 }
   1117 
   1118 static inline vnode_impl_t *
   1119 vcache_hash_lookup(const struct vcache_key *key, uint32_t hash)
   1120 {
   1121 	struct hashhead *hashp;
   1122 	vnode_impl_t *node;
   1123 
   1124 	KASSERT(mutex_owned(&vcache.lock));
   1125 
   1126 	hashp = &vcache.hashtab[hash & vcache.hashmask];
   1127 	SLIST_FOREACH(node, hashp, vi_hash) {
   1128 		if (key->vk_mount != node->vi_key.vk_mount)
   1129 			continue;
   1130 		if (key->vk_key_len != node->vi_key.vk_key_len)
   1131 			continue;
   1132 		if (memcmp(key->vk_key, node->vi_key.vk_key, key->vk_key_len))
   1133 			continue;
   1134 		return node;
   1135 	}
   1136 	return NULL;
   1137 }
   1138 
   1139 /*
   1140  * Allocate a new, uninitialized vcache node.
   1141  */
   1142 static vnode_impl_t *
   1143 vcache_alloc(void)
   1144 {
   1145 	vnode_impl_t *node;
   1146 	vnode_t *vp;
   1147 
   1148 	node = pool_cache_get(vcache.pool, PR_WAITOK);
   1149 	memset(node, 0, sizeof(*node));
   1150 
   1151 	/* SLIST_INIT(&node->vi_hash); */
   1152 
   1153 	vp = VIMPL_TO_VNODE(node);
   1154 	uvm_obj_init(&vp->v_uobj, &uvm_vnodeops, true, 0);
   1155 	cv_init(&vp->v_cv, "vnode");
   1156 	/* LIST_INIT(&vp->v_nclist); */
   1157 	/* LIST_INIT(&vp->v_dnclist); */
   1158 
   1159 	mutex_enter(&vnode_free_list_lock);
   1160 	numvnodes++;
   1161 	if (numvnodes > desiredvnodes + desiredvnodes / 10)
   1162 		cv_signal(&vdrain_cv);
   1163 	mutex_exit(&vnode_free_list_lock);
   1164 
   1165 	rw_init(&vp->v_lock);
   1166 	vp->v_usecount = 1;
   1167 	vp->v_type = VNON;
   1168 	vp->v_size = vp->v_writesize = VSIZENOTSET;
   1169 
   1170 	node->vi_state = VS_LOADING;
   1171 
   1172 	return node;
   1173 }
   1174 
   1175 /*
   1176  * Free an unused, unreferenced vcache node.
   1177  */
   1178 static void
   1179 vcache_free(vnode_impl_t *node)
   1180 {
   1181 	vnode_t *vp;
   1182 
   1183 	vp = VIMPL_TO_VNODE(node);
   1184 
   1185 	KASSERT(vp->v_usecount == 0);
   1186 
   1187 	rw_destroy(&vp->v_lock);
   1188 	mutex_enter(&vnode_free_list_lock);
   1189 	numvnodes--;
   1190 	mutex_exit(&vnode_free_list_lock);
   1191 
   1192 	uvm_obj_destroy(&vp->v_uobj, true);
   1193 	cv_destroy(&vp->v_cv);
   1194 	pool_cache_put(vcache.pool, node);
   1195 }
   1196 
   1197 /*
   1198  * Get a vnode / fs node pair by key and return it referenced through vpp.
   1199  */
   1200 int
   1201 vcache_get(struct mount *mp, const void *key, size_t key_len,
   1202     struct vnode **vpp)
   1203 {
   1204 	int error;
   1205 	uint32_t hash;
   1206 	const void *new_key;
   1207 	struct vnode *vp;
   1208 	struct vcache_key vcache_key;
   1209 	vnode_impl_t *node, *new_node;
   1210 
   1211 	new_key = NULL;
   1212 	*vpp = NULL;
   1213 
   1214 	vcache_key.vk_mount = mp;
   1215 	vcache_key.vk_key = key;
   1216 	vcache_key.vk_key_len = key_len;
   1217 	hash = vcache_hash(&vcache_key);
   1218 
   1219 again:
   1220 	mutex_enter(&vcache.lock);
   1221 	node = vcache_hash_lookup(&vcache_key, hash);
   1222 
   1223 	/* If found, take a reference or retry. */
   1224 	if (__predict_true(node != NULL)) {
   1225 		/*
   1226 		 * If the vnode is loading we cannot take the v_interlock
   1227 		 * here as it might change during load (see uvm_obj_setlock()).
   1228 		 * As changing state from VS_LOADING requires both vcache.lock
   1229 		 * and v_interlock it is safe to test with vcache.lock held.
   1230 		 *
   1231 		 * Wait for vnodes changing state from VS_LOADING and retry.
   1232 		 */
   1233 		if (__predict_false(node->vi_state == VS_LOADING)) {
   1234 			cv_wait(&vcache.cv, &vcache.lock);
   1235 			mutex_exit(&vcache.lock);
   1236 			goto again;
   1237 		}
   1238 		vp = VIMPL_TO_VNODE(node);
   1239 		mutex_enter(vp->v_interlock);
   1240 		mutex_exit(&vcache.lock);
   1241 		error = vget(vp, 0, true /* wait */);
   1242 		if (error == ENOENT)
   1243 			goto again;
   1244 		if (error == 0)
   1245 			*vpp = vp;
   1246 		KASSERT((error != 0) == (*vpp == NULL));
   1247 		return error;
   1248 	}
   1249 	mutex_exit(&vcache.lock);
   1250 
   1251 	/* Allocate and initialize a new vcache / vnode pair. */
   1252 	error = vfs_busy(mp, NULL);
   1253 	if (error)
   1254 		return error;
   1255 	new_node = vcache_alloc();
   1256 	new_node->vi_key = vcache_key;
   1257 	vp = VIMPL_TO_VNODE(new_node);
   1258 	mutex_enter(&vcache.lock);
   1259 	node = vcache_hash_lookup(&vcache_key, hash);
   1260 	if (node == NULL) {
   1261 		SLIST_INSERT_HEAD(&vcache.hashtab[hash & vcache.hashmask],
   1262 		    new_node, vi_hash);
   1263 		node = new_node;
   1264 	}
   1265 
   1266 	/* If another thread beat us inserting this node, retry. */
   1267 	if (node != new_node) {
   1268 		mutex_enter(vp->v_interlock);
   1269 		VSTATE_CHANGE(vp, VS_LOADING, VS_RECLAIMED);
   1270 		mutex_exit(&vcache.lock);
   1271 		vrelel(vp, 0);
   1272 		vfs_unbusy(mp, false, NULL);
   1273 		goto again;
   1274 	}
   1275 	mutex_exit(&vcache.lock);
   1276 
   1277 	/* Load the fs node.  Exclusive as new_node is VS_LOADING. */
   1278 	error = VFS_LOADVNODE(mp, vp, key, key_len, &new_key);
   1279 	if (error) {
   1280 		mutex_enter(&vcache.lock);
   1281 		SLIST_REMOVE(&vcache.hashtab[hash & vcache.hashmask],
   1282 		    new_node, vnode_impl, vi_hash);
   1283 		mutex_enter(vp->v_interlock);
   1284 		VSTATE_CHANGE(vp, VS_LOADING, VS_RECLAIMED);
   1285 		mutex_exit(&vcache.lock);
   1286 		vrelel(vp, 0);
   1287 		vfs_unbusy(mp, false, NULL);
   1288 		KASSERT(*vpp == NULL);
   1289 		return error;
   1290 	}
   1291 	KASSERT(new_key != NULL);
   1292 	KASSERT(memcmp(key, new_key, key_len) == 0);
   1293 	KASSERT(vp->v_op != NULL);
   1294 	vfs_insmntque(vp, mp);
   1295 	if ((mp->mnt_iflag & IMNT_MPSAFE) != 0)
   1296 		vp->v_vflag |= VV_MPSAFE;
   1297 	vfs_unbusy(mp, true, NULL);
   1298 
   1299 	/* Finished loading, finalize node. */
   1300 	mutex_enter(&vcache.lock);
   1301 	new_node->vi_key.vk_key = new_key;
   1302 	mutex_enter(vp->v_interlock);
   1303 	VSTATE_CHANGE(vp, VS_LOADING, VS_ACTIVE);
   1304 	mutex_exit(vp->v_interlock);
   1305 	mutex_exit(&vcache.lock);
   1306 	*vpp = vp;
   1307 	return 0;
   1308 }
   1309 
   1310 /*
   1311  * Create a new vnode / fs node pair and return it referenced through vpp.
   1312  */
   1313 int
   1314 vcache_new(struct mount *mp, struct vnode *dvp, struct vattr *vap,
   1315     kauth_cred_t cred, struct vnode **vpp)
   1316 {
   1317 	int error;
   1318 	uint32_t hash;
   1319 	struct vnode *ovp, *vp;
   1320 	vnode_impl_t *new_node;
   1321 	vnode_impl_t *old_node __diagused;
   1322 
   1323 	*vpp = NULL;
   1324 
   1325 	/* Allocate and initialize a new vcache / vnode pair. */
   1326 	error = vfs_busy(mp, NULL);
   1327 	if (error)
   1328 		return error;
   1329 	new_node = vcache_alloc();
   1330 	new_node->vi_key.vk_mount = mp;
   1331 	vp = VIMPL_TO_VNODE(new_node);
   1332 
   1333 	/* Create and load the fs node. */
   1334 	error = VFS_NEWVNODE(mp, dvp, vp, vap, cred,
   1335 	    &new_node->vi_key.vk_key_len, &new_node->vi_key.vk_key);
   1336 	if (error) {
   1337 		mutex_enter(&vcache.lock);
   1338 		mutex_enter(vp->v_interlock);
   1339 		VSTATE_CHANGE(vp, VS_LOADING, VS_RECLAIMED);
   1340 		mutex_exit(&vcache.lock);
   1341 		vrelel(vp, 0);
   1342 		vfs_unbusy(mp, false, NULL);
   1343 		KASSERT(*vpp == NULL);
   1344 		return error;
   1345 	}
   1346 	KASSERT(new_node->vi_key.vk_key != NULL);
   1347 	KASSERT(vp->v_op != NULL);
   1348 	hash = vcache_hash(&new_node->vi_key);
   1349 
   1350 	/* Wait for previous instance to be reclaimed, then insert new node. */
   1351 	mutex_enter(&vcache.lock);
   1352 	while ((old_node = vcache_hash_lookup(&new_node->vi_key, hash))) {
   1353 		ovp = VIMPL_TO_VNODE(old_node);
   1354 		mutex_enter(ovp->v_interlock);
   1355 		mutex_exit(&vcache.lock);
   1356 		error = vget(ovp, 0, true /* wait */);
   1357 		KASSERT(error == ENOENT);
   1358 		mutex_enter(&vcache.lock);
   1359 	}
   1360 	SLIST_INSERT_HEAD(&vcache.hashtab[hash & vcache.hashmask],
   1361 	    new_node, vi_hash);
   1362 	mutex_exit(&vcache.lock);
   1363 	vfs_insmntque(vp, mp);
   1364 	if ((mp->mnt_iflag & IMNT_MPSAFE) != 0)
   1365 		vp->v_vflag |= VV_MPSAFE;
   1366 	vfs_unbusy(mp, true, NULL);
   1367 
   1368 	/* Finished loading, finalize node. */
   1369 	mutex_enter(&vcache.lock);
   1370 	mutex_enter(vp->v_interlock);
   1371 	VSTATE_CHANGE(vp, VS_LOADING, VS_ACTIVE);
   1372 	mutex_exit(&vcache.lock);
   1373 	mutex_exit(vp->v_interlock);
   1374 	*vpp = vp;
   1375 	return 0;
   1376 }
   1377 
   1378 /*
   1379  * Prepare key change: lock old and new cache node.
   1380  * Return an error if the new node already exists.
   1381  */
   1382 int
   1383 vcache_rekey_enter(struct mount *mp, struct vnode *vp,
   1384     const void *old_key, size_t old_key_len,
   1385     const void *new_key, size_t new_key_len)
   1386 {
   1387 	uint32_t old_hash, new_hash;
   1388 	struct vcache_key old_vcache_key, new_vcache_key;
   1389 	vnode_impl_t *node, *new_node;
   1390 	struct vnode *tvp;
   1391 
   1392 	old_vcache_key.vk_mount = mp;
   1393 	old_vcache_key.vk_key = old_key;
   1394 	old_vcache_key.vk_key_len = old_key_len;
   1395 	old_hash = vcache_hash(&old_vcache_key);
   1396 
   1397 	new_vcache_key.vk_mount = mp;
   1398 	new_vcache_key.vk_key = new_key;
   1399 	new_vcache_key.vk_key_len = new_key_len;
   1400 	new_hash = vcache_hash(&new_vcache_key);
   1401 
   1402 	new_node = vcache_alloc();
   1403 	new_node->vi_key = new_vcache_key;
   1404 	tvp = VIMPL_TO_VNODE(new_node);
   1405 
   1406 	/* Insert locked new node used as placeholder. */
   1407 	mutex_enter(&vcache.lock);
   1408 	node = vcache_hash_lookup(&new_vcache_key, new_hash);
   1409 	if (node != NULL) {
   1410 		mutex_enter(tvp->v_interlock);
   1411 		VSTATE_CHANGE(tvp, VS_LOADING, VS_RECLAIMED);
   1412 		mutex_exit(&vcache.lock);
   1413 		vrelel(tvp, 0);
   1414 		return EEXIST;
   1415 	}
   1416 	SLIST_INSERT_HEAD(&vcache.hashtab[new_hash & vcache.hashmask],
   1417 	    new_node, vi_hash);
   1418 
   1419 	/* Lock old node. */
   1420 	node = vcache_hash_lookup(&old_vcache_key, old_hash);
   1421 	KASSERT(node != NULL);
   1422 	KASSERT(VIMPL_TO_VNODE(node) == vp);
   1423 	mutex_enter(vp->v_interlock);
   1424 	VSTATE_CHANGE(vp, VS_ACTIVE, VS_BLOCKED);
   1425 	node->vi_key = old_vcache_key;
   1426 	mutex_exit(vp->v_interlock);
   1427 	mutex_exit(&vcache.lock);
   1428 	return 0;
   1429 }
   1430 
   1431 /*
   1432  * Key change complete: remove old node and unlock new node.
   1433  */
   1434 void
   1435 vcache_rekey_exit(struct mount *mp, struct vnode *vp,
   1436     const void *old_key, size_t old_key_len,
   1437     const void *new_key, size_t new_key_len)
   1438 {
   1439 	uint32_t old_hash, new_hash;
   1440 	struct vcache_key old_vcache_key, new_vcache_key;
   1441 	vnode_impl_t *old_node, *new_node;
   1442 	struct vnode *tvp;
   1443 
   1444 	old_vcache_key.vk_mount = mp;
   1445 	old_vcache_key.vk_key = old_key;
   1446 	old_vcache_key.vk_key_len = old_key_len;
   1447 	old_hash = vcache_hash(&old_vcache_key);
   1448 
   1449 	new_vcache_key.vk_mount = mp;
   1450 	new_vcache_key.vk_key = new_key;
   1451 	new_vcache_key.vk_key_len = new_key_len;
   1452 	new_hash = vcache_hash(&new_vcache_key);
   1453 
   1454 	mutex_enter(&vcache.lock);
   1455 
   1456 	/* Lookup old and new node. */
   1457 	old_node = vcache_hash_lookup(&old_vcache_key, old_hash);
   1458 	KASSERT(old_node != NULL);
   1459 	KASSERT(VIMPL_TO_VNODE(old_node) == vp);
   1460 	mutex_enter(vp->v_interlock);
   1461 	VSTATE_ASSERT(vp, VS_BLOCKED);
   1462 
   1463 	new_node = vcache_hash_lookup(&new_vcache_key, new_hash);
   1464 	KASSERT(new_node != NULL);
   1465 	KASSERT(new_node->vi_key.vk_key_len == new_key_len);
   1466 	tvp = VIMPL_TO_VNODE(new_node);
   1467 	mutex_enter(tvp->v_interlock);
   1468 	VSTATE_ASSERT(VIMPL_TO_VNODE(new_node), VS_LOADING);
   1469 
   1470 	/* Rekey old node and put it onto its new hashlist. */
   1471 	old_node->vi_key = new_vcache_key;
   1472 	if (old_hash != new_hash) {
   1473 		SLIST_REMOVE(&vcache.hashtab[old_hash & vcache.hashmask],
   1474 		    old_node, vnode_impl, vi_hash);
   1475 		SLIST_INSERT_HEAD(&vcache.hashtab[new_hash & vcache.hashmask],
   1476 		    old_node, vi_hash);
   1477 	}
   1478 	VSTATE_CHANGE(vp, VS_BLOCKED, VS_ACTIVE);
   1479 	mutex_exit(vp->v_interlock);
   1480 
   1481 	/* Remove new node used as placeholder. */
   1482 	SLIST_REMOVE(&vcache.hashtab[new_hash & vcache.hashmask],
   1483 	    new_node, vnode_impl, vi_hash);
   1484 	VSTATE_CHANGE(tvp, VS_LOADING, VS_RECLAIMED);
   1485 	mutex_exit(&vcache.lock);
   1486 	vrelel(tvp, 0);
   1487 }
   1488 
   1489 /*
   1490  * Disassociate the underlying file system from a vnode.
   1491  *
   1492  * Must be called with vnode locked and will return unlocked.
   1493  * Must be called with the interlock held, and will return with it held.
   1494  */
   1495 static void
   1496 vcache_reclaim(vnode_t *vp)
   1497 {
   1498 	lwp_t *l = curlwp;
   1499 	vnode_impl_t *node = VNODE_TO_VIMPL(vp);
   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 = node->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 (node->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, node->vi_key.vk_key, temp_key_len);
   1533 	node->vi_key.vk_key = temp_key;
   1534 	mutex_exit(&vcache.lock);
   1535 
   1536 	/*
   1537 	 * Clean out any cached data associated with the vnode.
   1538 	 * If purging an active vnode, it must be closed and
   1539 	 * deactivated before being reclaimed. Note that the
   1540 	 * VOP_INACTIVE will unlock the vnode.
   1541 	 */
   1542 	error = vinvalbuf(vp, V_SAVE, NOCRED, l, 0, 0);
   1543 	if (error != 0) {
   1544 		if (wapbl_vphaswapbl(vp))
   1545 			WAPBL_DISCARD(wapbl_vptomp(vp));
   1546 		error = vinvalbuf(vp, 0, NOCRED, l, 0, 0);
   1547 	}
   1548 	KASSERTMSG((error == 0), "vinvalbuf failed: %d", error);
   1549 	KASSERT((vp->v_iflag & VI_ONWORKLST) == 0);
   1550 	if (active && (vp->v_type == VBLK || vp->v_type == VCHR)) {
   1551 		 spec_node_revoke(vp);
   1552 	}
   1553 	if (active) {
   1554 		VOP_INACTIVE(vp, &recycle);
   1555 	} else {
   1556 		/*
   1557 		 * Any other processes trying to obtain this lock must first
   1558 		 * wait for VS_RECLAIMED, then call the new lock operation.
   1559 		 */
   1560 		VOP_UNLOCK(vp);
   1561 	}
   1562 
   1563 	/* Disassociate the underlying file system from the vnode. */
   1564 	if (VOP_RECLAIM(vp)) {
   1565 		vnpanic(vp, "%s: cannot reclaim", __func__);
   1566 	}
   1567 
   1568 	KASSERT(vp->v_data == NULL);
   1569 	KASSERT(vp->v_uobj.uo_npages == 0);
   1570 
   1571 	if (vp->v_type == VREG && vp->v_ractx != NULL) {
   1572 		uvm_ra_freectx(vp->v_ractx);
   1573 		vp->v_ractx = NULL;
   1574 	}
   1575 
   1576 	/* Purge name cache. */
   1577 	cache_purge(vp);
   1578 
   1579 	/* Move to dead mount. */
   1580 	vp->v_vflag &= ~VV_ROOT;
   1581 	atomic_inc_uint(&dead_rootmount->mnt_refcnt);
   1582 	vfs_insmntque(vp, dead_rootmount);
   1583 
   1584 	/* Remove from vnode cache. */
   1585 	hash = vcache_hash(&node->vi_key);
   1586 	mutex_enter(&vcache.lock);
   1587 	KASSERT(node == vcache_hash_lookup(&node->vi_key, hash));
   1588 	SLIST_REMOVE(&vcache.hashtab[hash & vcache.hashmask],
   1589 	    node, vnode_impl, vi_hash);
   1590 	mutex_exit(&vcache.lock);
   1591 	if (temp_key != temp_buf)
   1592 		kmem_free(temp_key, temp_key_len);
   1593 
   1594 	/* Done with purge, notify sleepers of the grim news. */
   1595 	mutex_enter(vp->v_interlock);
   1596 	vp->v_op = dead_vnodeop_p;
   1597 	vp->v_vflag |= VV_LOCKSWORK;
   1598 	VSTATE_CHANGE(vp, VS_RECLAIMING, VS_RECLAIMED);
   1599 	vp->v_tag = VT_NON;
   1600 	KNOTE(&vp->v_klist, NOTE_REVOKE);
   1601 
   1602 	KASSERT((vp->v_iflag & VI_ONWORKLST) == 0);
   1603 }
   1604 
   1605 /*
   1606  * Print a vcache node.
   1607  */
   1608 void
   1609 vcache_print(vnode_t *vp, const char *prefix, void (*pr)(const char *, ...))
   1610 {
   1611 	int n;
   1612 	const uint8_t *cp;
   1613 	vnode_impl_t *node;
   1614 
   1615 	node = VNODE_TO_VIMPL(vp);
   1616 	n = node->vi_key.vk_key_len;
   1617 	cp = node->vi_key.vk_key;
   1618 
   1619 	(*pr)("%sstate %s, key(%d)", prefix, vstate_name(node->vi_state), n);
   1620 
   1621 	while (n-- > 0)
   1622 		(*pr)(" %02x", *cp++);
   1623 	(*pr)("\n");
   1624 }
   1625 
   1626 /*
   1627  * Update outstanding I/O count and do wakeup if requested.
   1628  */
   1629 void
   1630 vwakeup(struct buf *bp)
   1631 {
   1632 	vnode_t *vp;
   1633 
   1634 	if ((vp = bp->b_vp) == NULL)
   1635 		return;
   1636 
   1637 	KASSERT(bp->b_objlock == vp->v_interlock);
   1638 	KASSERT(mutex_owned(bp->b_objlock));
   1639 
   1640 	if (--vp->v_numoutput < 0)
   1641 		vnpanic(vp, "%s: neg numoutput, vp %p", __func__, vp);
   1642 	if (vp->v_numoutput == 0)
   1643 		cv_broadcast(&vp->v_cv);
   1644 }
   1645 
   1646 /*
   1647  * Test a vnode for being or becoming dead.  Returns one of:
   1648  * EBUSY:  vnode is becoming dead, with "flags == VDEAD_NOWAIT" only.
   1649  * ENOENT: vnode is dead.
   1650  * 0:      otherwise.
   1651  *
   1652  * Whenever this function returns a non-zero value all future
   1653  * calls will also return a non-zero value.
   1654  */
   1655 int
   1656 vdead_check(struct vnode *vp, int flags)
   1657 {
   1658 
   1659 	KASSERT(mutex_owned(vp->v_interlock));
   1660 
   1661 	if (! ISSET(flags, VDEAD_NOWAIT))
   1662 		VSTATE_WAIT_STABLE(vp);
   1663 
   1664 	if (VSTATE_GET(vp) == VS_RECLAIMING) {
   1665 		KASSERT(ISSET(flags, VDEAD_NOWAIT));
   1666 		return EBUSY;
   1667 	} else if (VSTATE_GET(vp) == VS_RECLAIMED) {
   1668 		return ENOENT;
   1669 	}
   1670 
   1671 	return 0;
   1672 }
   1673 
   1674 int
   1675 vfs_drainvnodes(long target)
   1676 {
   1677 	int error;
   1678 
   1679 	mutex_enter(&vnode_free_list_lock);
   1680 
   1681 	while (numvnodes > target) {
   1682 		error = cleanvnode();
   1683 		if (error != 0)
   1684 			return error;
   1685 		mutex_enter(&vnode_free_list_lock);
   1686 	}
   1687 
   1688 	mutex_exit(&vnode_free_list_lock);
   1689 
   1690 	vcache_reinit();
   1691 
   1692 	return 0;
   1693 }
   1694 
   1695 void
   1696 vnpanic(vnode_t *vp, const char *fmt, ...)
   1697 {
   1698 	va_list ap;
   1699 
   1700 #ifdef DIAGNOSTIC
   1701 	vprint(NULL, vp);
   1702 #endif
   1703 	va_start(ap, fmt);
   1704 	vpanic(fmt, ap);
   1705 	va_end(ap);
   1706 }
   1707