vfs_subr.c revision 169667
1/*-
2 * Copyright (c) 1989, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 * (c) UNIX System Laboratories, Inc.
5 * All or some portions of this file are derived from material licensed
6 * to the University of California by American Telephone and Telegraph
7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8 * the permission of UNIX System Laboratories, Inc.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 4. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 *
34 *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
35 */
36
37/*
38 * External virtual filesystem routines
39 */
40
41#include <sys/cdefs.h>
42__FBSDID("$FreeBSD: head/sys/kern/vfs_subr.c 169667 2007-05-18 07:10:50Z jeff $");
43
44#include "opt_ddb.h"
45#include "opt_mac.h"
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/bio.h>
50#include <sys/buf.h>
51#include <sys/conf.h>
52#include <sys/dirent.h>
53#include <sys/event.h>
54#include <sys/eventhandler.h>
55#include <sys/extattr.h>
56#include <sys/file.h>
57#include <sys/fcntl.h>
58#include <sys/jail.h>
59#include <sys/kdb.h>
60#include <sys/kernel.h>
61#include <sys/kthread.h>
62#include <sys/malloc.h>
63#include <sys/mount.h>
64#include <sys/namei.h>
65#include <sys/priv.h>
66#include <sys/reboot.h>
67#include <sys/sleepqueue.h>
68#include <sys/stat.h>
69#include <sys/sysctl.h>
70#include <sys/syslog.h>
71#include <sys/vmmeter.h>
72#include <sys/vnode.h>
73
74#include <machine/stdarg.h>
75
76#include <security/mac/mac_framework.h>
77
78#include <vm/vm.h>
79#include <vm/vm_object.h>
80#include <vm/vm_extern.h>
81#include <vm/pmap.h>
82#include <vm/vm_map.h>
83#include <vm/vm_page.h>
84#include <vm/vm_kern.h>
85#include <vm/uma.h>
86
87#ifdef DDB
88#include <ddb/ddb.h>
89#endif
90
91static MALLOC_DEFINE(M_NETADDR, "subr_export_host", "Export host address structure");
92
93static void	delmntque(struct vnode *vp);
94static int	flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
95		    int slpflag, int slptimeo);
96static void	syncer_shutdown(void *arg, int howto);
97static int	vtryrecycle(struct vnode *vp);
98static void	vbusy(struct vnode *vp);
99static void	vinactive(struct vnode *, struct thread *);
100static void	v_incr_usecount(struct vnode *);
101static void	v_decr_usecount(struct vnode *);
102static void	v_decr_useonly(struct vnode *);
103static void	v_upgrade_usecount(struct vnode *);
104static void	vfree(struct vnode *);
105static void	vnlru_free(int);
106static void	vdestroy(struct vnode *);
107static void	vgonel(struct vnode *);
108static void	vfs_knllock(void *arg);
109static void	vfs_knlunlock(void *arg);
110static int	vfs_knllocked(void *arg);
111
112
113/*
114 * Enable Giant pushdown based on whether or not the vm is mpsafe in this
115 * build.  Without mpsafevm the buffer cache can not run Giant free.
116 */
117int mpsafe_vfs = 1;
118TUNABLE_INT("debug.mpsafevfs", &mpsafe_vfs);
119SYSCTL_INT(_debug, OID_AUTO, mpsafevfs, CTLFLAG_RD, &mpsafe_vfs, 0,
120    "MPSAFE VFS");
121
122/*
123 * Number of vnodes in existence.  Increased whenever getnewvnode()
124 * allocates a new vnode, decreased on vdestroy() called on VI_DOOMed
125 * vnode.
126 */
127static unsigned long	numvnodes;
128
129SYSCTL_LONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
130
131/*
132 * Conversion tables for conversion from vnode types to inode formats
133 * and back.
134 */
135enum vtype iftovt_tab[16] = {
136	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
137	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
138};
139int vttoif_tab[10] = {
140	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
141	S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
142};
143
144/*
145 * List of vnodes that are ready for recycling.
146 */
147static TAILQ_HEAD(freelst, vnode) vnode_free_list;
148
149/*
150 * Free vnode target.  Free vnodes may simply be files which have been stat'd
151 * but not read.  This is somewhat common, and a small cache of such files
152 * should be kept to avoid recreation costs.
153 */
154static u_long wantfreevnodes;
155SYSCTL_LONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
156/* Number of vnodes in the free list. */
157static u_long freevnodes;
158SYSCTL_LONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
159
160/*
161 * Various variables used for debugging the new implementation of
162 * reassignbuf().
163 * XXX these are probably of (very) limited utility now.
164 */
165static int reassignbufcalls;
166SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
167
168/*
169 * Cache for the mount type id assigned to NFS.  This is used for
170 * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
171 */
172int	nfs_mount_type = -1;
173
174/* To keep more than one thread at a time from running vfs_getnewfsid */
175static struct mtx mntid_mtx;
176
177/*
178 * Lock for any access to the following:
179 *	vnode_free_list
180 *	numvnodes
181 *	freevnodes
182 */
183static struct mtx vnode_free_list_mtx;
184
185/* Publicly exported FS */
186struct nfs_public nfs_pub;
187
188/* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
189static uma_zone_t vnode_zone;
190static uma_zone_t vnodepoll_zone;
191
192/* Set to 1 to print out reclaim of active vnodes */
193int	prtactive;
194
195/*
196 * The workitem queue.
197 *
198 * It is useful to delay writes of file data and filesystem metadata
199 * for tens of seconds so that quickly created and deleted files need
200 * not waste disk bandwidth being created and removed. To realize this,
201 * we append vnodes to a "workitem" queue. When running with a soft
202 * updates implementation, most pending metadata dependencies should
203 * not wait for more than a few seconds. Thus, mounted on block devices
204 * are delayed only about a half the time that file data is delayed.
205 * Similarly, directory updates are more critical, so are only delayed
206 * about a third the time that file data is delayed. Thus, there are
207 * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
208 * one each second (driven off the filesystem syncer process). The
209 * syncer_delayno variable indicates the next queue that is to be processed.
210 * Items that need to be processed soon are placed in this queue:
211 *
212 *	syncer_workitem_pending[syncer_delayno]
213 *
214 * A delay of fifteen seconds is done by placing the request fifteen
215 * entries later in the queue:
216 *
217 *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
218 *
219 */
220static int syncer_delayno;
221static long syncer_mask;
222LIST_HEAD(synclist, bufobj);
223static struct synclist *syncer_workitem_pending;
224/*
225 * The sync_mtx protects:
226 *	bo->bo_synclist
227 *	sync_vnode_count
228 *	syncer_delayno
229 *	syncer_state
230 *	syncer_workitem_pending
231 *	syncer_worklist_len
232 *	rushjob
233 */
234static struct mtx sync_mtx;
235
236#define SYNCER_MAXDELAY		32
237static int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
238static int syncdelay = 30;		/* max time to delay syncing data */
239static int filedelay = 30;		/* time to delay syncing files */
240SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
241static int dirdelay = 29;		/* time to delay syncing directories */
242SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
243static int metadelay = 28;		/* time to delay syncing metadata */
244SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
245static int rushjob;		/* number of slots to run ASAP */
246static int stat_rush_requests;	/* number of times I/O speeded up */
247SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
248
249/*
250 * When shutting down the syncer, run it at four times normal speed.
251 */
252#define SYNCER_SHUTDOWN_SPEEDUP		4
253static int sync_vnode_count;
254static int syncer_worklist_len;
255static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
256    syncer_state;
257
258/*
259 * Number of vnodes we want to exist at any one time.  This is mostly used
260 * to size hash tables in vnode-related code.  It is normally not used in
261 * getnewvnode(), as wantfreevnodes is normally nonzero.)
262 *
263 * XXX desiredvnodes is historical cruft and should not exist.
264 */
265int desiredvnodes;
266SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
267    &desiredvnodes, 0, "Maximum number of vnodes");
268SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
269    &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
270static int vnlru_nowhere;
271SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
272    &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
273
274/*
275 * Macros to control when a vnode is freed and recycled.  All require
276 * the vnode interlock.
277 */
278#define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
279#define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
280#define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
281
282
283/*
284 * Initialize the vnode management data structures.
285 */
286#ifndef	MAXVNODES_MAX
287#define	MAXVNODES_MAX	100000
288#endif
289static void
290vntblinit(void *dummy __unused)
291{
292
293	/*
294	 * Desiredvnodes is a function of the physical memory size and
295	 * the kernel's heap size.  Specifically, desiredvnodes scales
296	 * in proportion to the physical memory size until two fifths
297	 * of the kernel's heap size is consumed by vnodes and vm
298	 * objects.
299	 */
300	desiredvnodes = min(maxproc + VMCNT_GET(page_count) / 4, 2 *
301	    vm_kmem_size / (5 * (sizeof(struct vm_object) +
302	    sizeof(struct vnode))));
303	if (desiredvnodes > MAXVNODES_MAX) {
304		if (bootverbose)
305			printf("Reducing kern.maxvnodes %d -> %d\n",
306			    desiredvnodes, MAXVNODES_MAX);
307		desiredvnodes = MAXVNODES_MAX;
308	}
309	wantfreevnodes = desiredvnodes / 4;
310	mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
311	TAILQ_INIT(&vnode_free_list);
312	mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
313	vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
314	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
315	vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
316	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
317	/*
318	 * Initialize the filesystem syncer.
319	 */
320	syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
321		&syncer_mask);
322	syncer_maxdelay = syncer_mask + 1;
323	mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
324}
325SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL)
326
327
328/*
329 * Mark a mount point as busy. Used to synchronize access and to delay
330 * unmounting. Interlock is not released on failure.
331 */
332int
333vfs_busy(struct mount *mp, int flags, struct mtx *interlkp,
334    struct thread *td)
335{
336	int lkflags;
337
338	MNT_ILOCK(mp);
339	MNT_REF(mp);
340	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
341		if (flags & LK_NOWAIT) {
342			MNT_REL(mp);
343			MNT_IUNLOCK(mp);
344			return (ENOENT);
345		}
346		if (interlkp)
347			mtx_unlock(interlkp);
348		mp->mnt_kern_flag |= MNTK_MWAIT;
349		/*
350		 * Since all busy locks are shared except the exclusive
351		 * lock granted when unmounting, the only place that a
352		 * wakeup needs to be done is at the release of the
353		 * exclusive lock at the end of dounmount.
354		 */
355		msleep(mp, MNT_MTX(mp), PVFS, "vfs_busy", 0);
356		MNT_REL(mp);
357		MNT_IUNLOCK(mp);
358		if (interlkp)
359			mtx_lock(interlkp);
360		return (ENOENT);
361	}
362	if (interlkp)
363		mtx_unlock(interlkp);
364	lkflags = LK_SHARED | LK_INTERLOCK;
365	if (lockmgr(&mp->mnt_lock, lkflags, MNT_MTX(mp), td))
366		panic("vfs_busy: unexpected lock failure");
367	return (0);
368}
369
370/*
371 * Free a busy filesystem.
372 */
373void
374vfs_unbusy(struct mount *mp, struct thread *td)
375{
376
377	lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, td);
378	vfs_rel(mp);
379}
380
381/*
382 * Lookup a mount point by filesystem identifier.
383 */
384struct mount *
385vfs_getvfs(fsid_t *fsid)
386{
387	struct mount *mp;
388
389	mtx_lock(&mountlist_mtx);
390	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
391		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
392		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
393			vfs_ref(mp);
394			mtx_unlock(&mountlist_mtx);
395			return (mp);
396		}
397	}
398	mtx_unlock(&mountlist_mtx);
399	return ((struct mount *) 0);
400}
401
402/*
403 * Check if a user can access privileged mount options.
404 */
405int
406vfs_suser(struct mount *mp, struct thread *td)
407{
408	int error;
409
410	/*
411	 * If the thread is jailed, but this is not a jail-friendly file
412	 * system, deny immediately.
413	 */
414	if (jailed(td->td_ucred) && !(mp->mnt_vfc->vfc_flags & VFCF_JAIL))
415		return (EPERM);
416
417	/*
418	 * If the file system was mounted outside a jail and a jailed thread
419	 * tries to access it, deny immediately.
420	 */
421	if (!jailed(mp->mnt_cred) && jailed(td->td_ucred))
422		return (EPERM);
423
424	/*
425	 * If the file system was mounted inside different jail that the jail of
426	 * the calling thread, deny immediately.
427	 */
428	if (jailed(mp->mnt_cred) && jailed(td->td_ucred) &&
429	    mp->mnt_cred->cr_prison != td->td_ucred->cr_prison) {
430		return (EPERM);
431	}
432
433	if ((mp->mnt_flag & MNT_USER) == 0 ||
434	    mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
435		if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
436			return (error);
437	}
438	return (0);
439}
440
441/*
442 * Get a new unique fsid.  Try to make its val[0] unique, since this value
443 * will be used to create fake device numbers for stat().  Also try (but
444 * not so hard) make its val[0] unique mod 2^16, since some emulators only
445 * support 16-bit device numbers.  We end up with unique val[0]'s for the
446 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
447 *
448 * Keep in mind that several mounts may be running in parallel.  Starting
449 * the search one past where the previous search terminated is both a
450 * micro-optimization and a defense against returning the same fsid to
451 * different mounts.
452 */
453void
454vfs_getnewfsid(struct mount *mp)
455{
456	static u_int16_t mntid_base;
457	struct mount *nmp;
458	fsid_t tfsid;
459	int mtype;
460
461	mtx_lock(&mntid_mtx);
462	mtype = mp->mnt_vfc->vfc_typenum;
463	tfsid.val[1] = mtype;
464	mtype = (mtype & 0xFF) << 24;
465	for (;;) {
466		tfsid.val[0] = makedev(255,
467		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
468		mntid_base++;
469		if ((nmp = vfs_getvfs(&tfsid)) == NULL)
470			break;
471		vfs_rel(nmp);
472	}
473	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
474	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
475	mtx_unlock(&mntid_mtx);
476}
477
478/*
479 * Knob to control the precision of file timestamps:
480 *
481 *   0 = seconds only; nanoseconds zeroed.
482 *   1 = seconds and nanoseconds, accurate within 1/HZ.
483 *   2 = seconds and nanoseconds, truncated to microseconds.
484 * >=3 = seconds and nanoseconds, maximum precision.
485 */
486enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
487
488static int timestamp_precision = TSP_SEC;
489SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
490    &timestamp_precision, 0, "");
491
492/*
493 * Get a current timestamp.
494 */
495void
496vfs_timestamp(struct timespec *tsp)
497{
498	struct timeval tv;
499
500	switch (timestamp_precision) {
501	case TSP_SEC:
502		tsp->tv_sec = time_second;
503		tsp->tv_nsec = 0;
504		break;
505	case TSP_HZ:
506		getnanotime(tsp);
507		break;
508	case TSP_USEC:
509		microtime(&tv);
510		TIMEVAL_TO_TIMESPEC(&tv, tsp);
511		break;
512	case TSP_NSEC:
513	default:
514		nanotime(tsp);
515		break;
516	}
517}
518
519/*
520 * Set vnode attributes to VNOVAL
521 */
522void
523vattr_null(struct vattr *vap)
524{
525
526	vap->va_type = VNON;
527	vap->va_size = VNOVAL;
528	vap->va_bytes = VNOVAL;
529	vap->va_mode = VNOVAL;
530	vap->va_nlink = VNOVAL;
531	vap->va_uid = VNOVAL;
532	vap->va_gid = VNOVAL;
533	vap->va_fsid = VNOVAL;
534	vap->va_fileid = VNOVAL;
535	vap->va_blocksize = VNOVAL;
536	vap->va_rdev = VNOVAL;
537	vap->va_atime.tv_sec = VNOVAL;
538	vap->va_atime.tv_nsec = VNOVAL;
539	vap->va_mtime.tv_sec = VNOVAL;
540	vap->va_mtime.tv_nsec = VNOVAL;
541	vap->va_ctime.tv_sec = VNOVAL;
542	vap->va_ctime.tv_nsec = VNOVAL;
543	vap->va_birthtime.tv_sec = VNOVAL;
544	vap->va_birthtime.tv_nsec = VNOVAL;
545	vap->va_flags = VNOVAL;
546	vap->va_gen = VNOVAL;
547	vap->va_vaflags = 0;
548}
549
550/*
551 * This routine is called when we have too many vnodes.  It attempts
552 * to free <count> vnodes and will potentially free vnodes that still
553 * have VM backing store (VM backing store is typically the cause
554 * of a vnode blowout so we want to do this).  Therefore, this operation
555 * is not considered cheap.
556 *
557 * A number of conditions may prevent a vnode from being reclaimed.
558 * the buffer cache may have references on the vnode, a directory
559 * vnode may still have references due to the namei cache representing
560 * underlying files, or the vnode may be in active use.   It is not
561 * desireable to reuse such vnodes.  These conditions may cause the
562 * number of vnodes to reach some minimum value regardless of what
563 * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
564 */
565static int
566vlrureclaim(struct mount *mp)
567{
568	struct thread *td;
569	struct vnode *vp;
570	int done;
571	int trigger;
572	int usevnodes;
573	int count;
574
575	/*
576	 * Calculate the trigger point, don't allow user
577	 * screwups to blow us up.   This prevents us from
578	 * recycling vnodes with lots of resident pages.  We
579	 * aren't trying to free memory, we are trying to
580	 * free vnodes.
581	 */
582	usevnodes = desiredvnodes;
583	if (usevnodes <= 0)
584		usevnodes = 1;
585	trigger = VMCNT_GET(page_count) * 2 / usevnodes;
586	done = 0;
587	td = curthread;
588	vn_start_write(NULL, &mp, V_WAIT);
589	MNT_ILOCK(mp);
590	count = mp->mnt_nvnodelistsize / 10 + 1;
591	while (count != 0) {
592		vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
593		while (vp != NULL && vp->v_type == VMARKER)
594			vp = TAILQ_NEXT(vp, v_nmntvnodes);
595		if (vp == NULL)
596			break;
597		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
598		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
599		--count;
600		if (!VI_TRYLOCK(vp))
601			goto next_iter;
602		/*
603		 * If it's been deconstructed already, it's still
604		 * referenced, or it exceeds the trigger, skip it.
605		 */
606		if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
607		    (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
608		    vp->v_object->resident_page_count > trigger)) {
609			VI_UNLOCK(vp);
610			goto next_iter;
611		}
612		MNT_IUNLOCK(mp);
613		vholdl(vp);
614		if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT, td)) {
615			vdrop(vp);
616			goto next_iter_mntunlocked;
617		}
618		VI_LOCK(vp);
619		/*
620		 * v_usecount may have been bumped after VOP_LOCK() dropped
621		 * the vnode interlock and before it was locked again.
622		 *
623		 * It is not necessary to recheck VI_DOOMED because it can
624		 * only be set by another thread that holds both the vnode
625		 * lock and vnode interlock.  If another thread has the
626		 * vnode lock before we get to VOP_LOCK() and obtains the
627		 * vnode interlock after VOP_LOCK() drops the vnode
628		 * interlock, the other thread will be unable to drop the
629		 * vnode lock before our VOP_LOCK() call fails.
630		 */
631		if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
632		    (vp->v_object != NULL &&
633		    vp->v_object->resident_page_count > trigger)) {
634			VOP_UNLOCK(vp, LK_INTERLOCK, td);
635			goto next_iter_mntunlocked;
636		}
637		KASSERT((vp->v_iflag & VI_DOOMED) == 0,
638		    ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
639		vgonel(vp);
640		VOP_UNLOCK(vp, 0, td);
641		vdropl(vp);
642		done++;
643next_iter_mntunlocked:
644		if ((count % 256) != 0)
645			goto relock_mnt;
646		goto yield;
647next_iter:
648		if ((count % 256) != 0)
649			continue;
650		MNT_IUNLOCK(mp);
651yield:
652		uio_yield();
653relock_mnt:
654		MNT_ILOCK(mp);
655	}
656	MNT_IUNLOCK(mp);
657	vn_finished_write(mp);
658	return done;
659}
660
661/*
662 * Attempt to keep the free list at wantfreevnodes length.
663 */
664static void
665vnlru_free(int count)
666{
667	struct vnode *vp;
668	int vfslocked;
669
670	mtx_assert(&vnode_free_list_mtx, MA_OWNED);
671	for (; count > 0; count--) {
672		vp = TAILQ_FIRST(&vnode_free_list);
673		/*
674		 * The list can be modified while the free_list_mtx
675		 * has been dropped and vp could be NULL here.
676		 */
677		if (!vp)
678			break;
679		VNASSERT(vp->v_op != NULL, vp,
680		    ("vnlru_free: vnode already reclaimed."));
681		TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
682		/*
683		 * Don't recycle if we can't get the interlock.
684		 */
685		if (!VI_TRYLOCK(vp)) {
686			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
687			continue;
688		}
689		VNASSERT(VCANRECYCLE(vp), vp,
690		    ("vp inconsistent on freelist"));
691		freevnodes--;
692		vp->v_iflag &= ~VI_FREE;
693		vholdl(vp);
694		mtx_unlock(&vnode_free_list_mtx);
695		VI_UNLOCK(vp);
696		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
697		vtryrecycle(vp);
698		VFS_UNLOCK_GIANT(vfslocked);
699		/*
700		 * If the recycled succeeded this vdrop will actually free
701		 * the vnode.  If not it will simply place it back on
702		 * the free list.
703		 */
704		vdrop(vp);
705		mtx_lock(&vnode_free_list_mtx);
706	}
707}
708/*
709 * Attempt to recycle vnodes in a context that is always safe to block.
710 * Calling vlrurecycle() from the bowels of filesystem code has some
711 * interesting deadlock problems.
712 */
713static struct proc *vnlruproc;
714static int vnlruproc_sig;
715
716static void
717vnlru_proc(void)
718{
719	struct mount *mp, *nmp;
720	int done;
721	struct proc *p = vnlruproc;
722	struct thread *td = FIRST_THREAD_IN_PROC(p);
723
724	mtx_lock(&Giant);
725
726	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
727	    SHUTDOWN_PRI_FIRST);
728
729	for (;;) {
730		kthread_suspend_check(p);
731		mtx_lock(&vnode_free_list_mtx);
732		if (freevnodes > wantfreevnodes)
733			vnlru_free(freevnodes - wantfreevnodes);
734		if (numvnodes <= desiredvnodes * 9 / 10) {
735			vnlruproc_sig = 0;
736			wakeup(&vnlruproc_sig);
737			msleep(vnlruproc, &vnode_free_list_mtx,
738			    PVFS|PDROP, "vlruwt", hz);
739			continue;
740		}
741		mtx_unlock(&vnode_free_list_mtx);
742		done = 0;
743		mtx_lock(&mountlist_mtx);
744		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
745			int vfsunlocked;
746			if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td)) {
747				nmp = TAILQ_NEXT(mp, mnt_list);
748				continue;
749			}
750			if (!VFS_NEEDSGIANT(mp)) {
751				mtx_unlock(&Giant);
752				vfsunlocked = 1;
753			} else
754				vfsunlocked = 0;
755			done += vlrureclaim(mp);
756			if (vfsunlocked)
757				mtx_lock(&Giant);
758			mtx_lock(&mountlist_mtx);
759			nmp = TAILQ_NEXT(mp, mnt_list);
760			vfs_unbusy(mp, td);
761		}
762		mtx_unlock(&mountlist_mtx);
763		if (done == 0) {
764			EVENTHANDLER_INVOKE(vfs_lowvnodes, desiredvnodes / 10);
765#if 0
766			/* These messages are temporary debugging aids */
767			if (vnlru_nowhere < 5)
768				printf("vnlru process getting nowhere..\n");
769			else if (vnlru_nowhere == 5)
770				printf("vnlru process messages stopped.\n");
771#endif
772			vnlru_nowhere++;
773			tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
774		} else
775			uio_yield();
776	}
777}
778
779static struct kproc_desc vnlru_kp = {
780	"vnlru",
781	vnlru_proc,
782	&vnlruproc
783};
784SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &vnlru_kp)
785
786/*
787 * Routines having to do with the management of the vnode table.
788 */
789
790static void
791vdestroy(struct vnode *vp)
792{
793	struct bufobj *bo;
794
795	CTR1(KTR_VFS, "vdestroy vp %p", vp);
796	mtx_lock(&vnode_free_list_mtx);
797	numvnodes--;
798	mtx_unlock(&vnode_free_list_mtx);
799	bo = &vp->v_bufobj;
800	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
801	    ("cleaned vnode still on the free list."));
802	VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
803	VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
804	VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
805	VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
806	VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
807	VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
808	VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
809	VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
810	VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
811	VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
812	VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
813	VI_UNLOCK(vp);
814#ifdef MAC
815	mac_destroy_vnode(vp);
816#endif
817	if (vp->v_pollinfo != NULL) {
818		knlist_destroy(&vp->v_pollinfo->vpi_selinfo.si_note);
819		mtx_destroy(&vp->v_pollinfo->vpi_lock);
820		uma_zfree(vnodepoll_zone, vp->v_pollinfo);
821	}
822#ifdef INVARIANTS
823	/* XXX Elsewhere we can detect an already freed vnode via NULL v_op. */
824	vp->v_op = NULL;
825#endif
826	lockdestroy(vp->v_vnlock);
827	mtx_destroy(&vp->v_interlock);
828	uma_zfree(vnode_zone, vp);
829}
830
831/*
832 * Try to recycle a freed vnode.  We abort if anyone picks up a reference
833 * before we actually vgone().  This function must be called with the vnode
834 * held to prevent the vnode from being returned to the free list midway
835 * through vgone().
836 */
837static int
838vtryrecycle(struct vnode *vp)
839{
840	struct thread *td = curthread;
841	struct mount *vnmp;
842
843	CTR1(KTR_VFS, "vtryrecycle: trying vp %p", vp);
844	VNASSERT(vp->v_holdcnt, vp,
845	    ("vtryrecycle: Recycling vp %p without a reference.", vp));
846	/*
847	 * This vnode may found and locked via some other list, if so we
848	 * can't recycle it yet.
849	 */
850	if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT, td) != 0)
851		return (EWOULDBLOCK);
852	/*
853	 * Don't recycle if its filesystem is being suspended.
854	 */
855	if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
856		VOP_UNLOCK(vp, 0, td);
857		return (EBUSY);
858	}
859	/*
860	 * If we got this far, we need to acquire the interlock and see if
861	 * anyone picked up this vnode from another list.  If not, we will
862	 * mark it with DOOMED via vgonel() so that anyone who does find it
863	 * will skip over it.
864	 */
865	VI_LOCK(vp);
866	if (vp->v_usecount) {
867		VOP_UNLOCK(vp, LK_INTERLOCK, td);
868		vn_finished_write(vnmp);
869		return (EBUSY);
870	}
871	if ((vp->v_iflag & VI_DOOMED) == 0)
872		vgonel(vp);
873	VOP_UNLOCK(vp, LK_INTERLOCK, td);
874	vn_finished_write(vnmp);
875	CTR1(KTR_VFS, "vtryrecycle: recycled vp %p", vp);
876	return (0);
877}
878
879/*
880 * Return the next vnode from the free list.
881 */
882int
883getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
884    struct vnode **vpp)
885{
886	struct vnode *vp = NULL;
887	struct bufobj *bo;
888
889	mtx_lock(&vnode_free_list_mtx);
890	/*
891	 * Lend our context to reclaim vnodes if they've exceeded the max.
892	 */
893	if (freevnodes > wantfreevnodes)
894		vnlru_free(1);
895	/*
896	 * Wait for available vnodes.
897	 */
898	if (numvnodes > desiredvnodes) {
899		if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
900			/*
901			 * File system is beeing suspended, we cannot risk a
902			 * deadlock here, so allocate new vnode anyway.
903			 */
904			if (freevnodes > wantfreevnodes)
905				vnlru_free(freevnodes - wantfreevnodes);
906			goto alloc;
907		}
908		if (vnlruproc_sig == 0) {
909			vnlruproc_sig = 1;	/* avoid unnecessary wakeups */
910			wakeup(vnlruproc);
911		}
912		msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
913		    "vlruwk", hz);
914#if 0	/* XXX Not all VFS_VGET/ffs_vget callers check returns. */
915		if (numvnodes > desiredvnodes) {
916			mtx_unlock(&vnode_free_list_mtx);
917			return (ENFILE);
918		}
919#endif
920	}
921alloc:
922	numvnodes++;
923	mtx_unlock(&vnode_free_list_mtx);
924	vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
925	/*
926	 * Setup locks.
927	 */
928	vp->v_vnlock = &vp->v_lock;
929	mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
930	/*
931	 * By default, don't allow shared locks unless filesystems
932	 * opt-in.
933	 */
934	lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
935	/*
936	 * Initialize bufobj.
937	 */
938	bo = &vp->v_bufobj;
939	bo->__bo_vnode = vp;
940	bo->bo_mtx = &vp->v_interlock;
941	bo->bo_ops = &buf_ops_bio;
942	bo->bo_private = vp;
943	TAILQ_INIT(&bo->bo_clean.bv_hd);
944	TAILQ_INIT(&bo->bo_dirty.bv_hd);
945	/*
946	 * Initialize namecache.
947	 */
948	LIST_INIT(&vp->v_cache_src);
949	TAILQ_INIT(&vp->v_cache_dst);
950	/*
951	 * Finalize various vnode identity bits.
952	 */
953	vp->v_type = VNON;
954	vp->v_tag = tag;
955	vp->v_op = vops;
956	v_incr_usecount(vp);
957	vp->v_data = 0;
958#ifdef MAC
959	mac_init_vnode(vp);
960	if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
961		mac_associate_vnode_singlelabel(mp, vp);
962	else if (mp == NULL)
963		printf("NULL mp in getnewvnode()\n");
964#endif
965	if (mp != NULL) {
966		bo->bo_bsize = mp->mnt_stat.f_iosize;
967		if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
968			vp->v_vflag |= VV_NOKNOTE;
969	}
970
971	CTR2(KTR_VFS, "getnewvnode: mp %p vp %p", mp, vp);
972	*vpp = vp;
973	return (0);
974}
975
976/*
977 * Delete from old mount point vnode list, if on one.
978 */
979static void
980delmntque(struct vnode *vp)
981{
982	struct mount *mp;
983
984	mp = vp->v_mount;
985	if (mp == NULL)
986		return;
987	MNT_ILOCK(mp);
988	vp->v_mount = NULL;
989	VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
990		("bad mount point vnode list size"));
991	TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
992	mp->mnt_nvnodelistsize--;
993	MNT_REL(mp);
994	MNT_IUNLOCK(mp);
995}
996
997static void
998insmntque_stddtr(struct vnode *vp, void *dtr_arg)
999{
1000	struct thread *td;
1001
1002	td = curthread; /* XXX ? */
1003	vp->v_data = NULL;
1004	vp->v_op = &dead_vnodeops;
1005	/* XXX non mp-safe fs may still call insmntque with vnode
1006	   unlocked */
1007	if (!VOP_ISLOCKED(vp, td))
1008		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1009	vgone(vp);
1010	vput(vp);
1011}
1012
1013/*
1014 * Insert into list of vnodes for the new mount point, if available.
1015 */
1016int
1017insmntque1(struct vnode *vp, struct mount *mp,
1018	void (*dtr)(struct vnode *, void *), void *dtr_arg)
1019{
1020
1021	KASSERT(vp->v_mount == NULL,
1022		("insmntque: vnode already on per mount vnode list"));
1023	VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1024	MNT_ILOCK(mp);
1025	if ((mp->mnt_kern_flag & MNTK_UNMOUNT) != 0 &&
1026	    mp->mnt_nvnodelistsize == 0) {
1027		MNT_IUNLOCK(mp);
1028		if (dtr != NULL)
1029			dtr(vp, dtr_arg);
1030		return (EBUSY);
1031	}
1032	vp->v_mount = mp;
1033	MNT_REF(mp);
1034	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1035	VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1036		("neg mount point vnode list size"));
1037	mp->mnt_nvnodelistsize++;
1038	MNT_IUNLOCK(mp);
1039	return (0);
1040}
1041
1042int
1043insmntque(struct vnode *vp, struct mount *mp)
1044{
1045
1046	return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1047}
1048
1049/*
1050 * Flush out and invalidate all buffers associated with a bufobj
1051 * Called with the underlying object locked.
1052 */
1053int
1054bufobj_invalbuf(struct bufobj *bo, int flags, struct thread *td, int slpflag,
1055    int slptimeo)
1056{
1057	int error;
1058
1059	BO_LOCK(bo);
1060	if (flags & V_SAVE) {
1061		error = bufobj_wwait(bo, slpflag, slptimeo);
1062		if (error) {
1063			BO_UNLOCK(bo);
1064			return (error);
1065		}
1066		if (bo->bo_dirty.bv_cnt > 0) {
1067			BO_UNLOCK(bo);
1068			if ((error = BO_SYNC(bo, MNT_WAIT, td)) != 0)
1069				return (error);
1070			/*
1071			 * XXX We could save a lock/unlock if this was only
1072			 * enabled under INVARIANTS
1073			 */
1074			BO_LOCK(bo);
1075			if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1076				panic("vinvalbuf: dirty bufs");
1077		}
1078	}
1079	/*
1080	 * If you alter this loop please notice that interlock is dropped and
1081	 * reacquired in flushbuflist.  Special care is needed to ensure that
1082	 * no race conditions occur from this.
1083	 */
1084	do {
1085		error = flushbuflist(&bo->bo_clean,
1086		    flags, bo, slpflag, slptimeo);
1087		if (error == 0)
1088			error = flushbuflist(&bo->bo_dirty,
1089			    flags, bo, slpflag, slptimeo);
1090		if (error != 0 && error != EAGAIN) {
1091			BO_UNLOCK(bo);
1092			return (error);
1093		}
1094	} while (error != 0);
1095
1096	/*
1097	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1098	 * have write I/O in-progress but if there is a VM object then the
1099	 * VM object can also have read-I/O in-progress.
1100	 */
1101	do {
1102		bufobj_wwait(bo, 0, 0);
1103		BO_UNLOCK(bo);
1104		if (bo->bo_object != NULL) {
1105			VM_OBJECT_LOCK(bo->bo_object);
1106			vm_object_pip_wait(bo->bo_object, "bovlbx");
1107			VM_OBJECT_UNLOCK(bo->bo_object);
1108		}
1109		BO_LOCK(bo);
1110	} while (bo->bo_numoutput > 0);
1111	BO_UNLOCK(bo);
1112
1113	/*
1114	 * Destroy the copy in the VM cache, too.
1115	 */
1116	if (bo->bo_object != NULL) {
1117		VM_OBJECT_LOCK(bo->bo_object);
1118		vm_object_page_remove(bo->bo_object, 0, 0,
1119			(flags & V_SAVE) ? TRUE : FALSE);
1120		VM_OBJECT_UNLOCK(bo->bo_object);
1121	}
1122
1123#ifdef INVARIANTS
1124	BO_LOCK(bo);
1125	if ((flags & (V_ALT | V_NORMAL)) == 0 &&
1126	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1127		panic("vinvalbuf: flush failed");
1128	BO_UNLOCK(bo);
1129#endif
1130	return (0);
1131}
1132
1133/*
1134 * Flush out and invalidate all buffers associated with a vnode.
1135 * Called with the underlying object locked.
1136 */
1137int
1138vinvalbuf(struct vnode *vp, int flags, struct thread *td, int slpflag,
1139    int slptimeo)
1140{
1141
1142	CTR2(KTR_VFS, "vinvalbuf vp %p flags %d", vp, flags);
1143	ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1144	return (bufobj_invalbuf(&vp->v_bufobj, flags, td, slpflag, slptimeo));
1145}
1146
1147/*
1148 * Flush out buffers on the specified list.
1149 *
1150 */
1151static int
1152flushbuflist( struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1153    int slptimeo)
1154{
1155	struct buf *bp, *nbp;
1156	int retval, error;
1157	daddr_t lblkno;
1158	b_xflags_t xflags;
1159
1160	ASSERT_BO_LOCKED(bo);
1161
1162	retval = 0;
1163	TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1164		if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1165		    ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1166			continue;
1167		}
1168		lblkno = 0;
1169		xflags = 0;
1170		if (nbp != NULL) {
1171			lblkno = nbp->b_lblkno;
1172			xflags = nbp->b_xflags &
1173				(BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
1174		}
1175		retval = EAGAIN;
1176		error = BUF_TIMELOCK(bp,
1177		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1178		    "flushbuf", slpflag, slptimeo);
1179		if (error) {
1180			BO_LOCK(bo);
1181			return (error != ENOLCK ? error : EAGAIN);
1182		}
1183		KASSERT(bp->b_bufobj == bo,
1184		    ("bp %p wrong b_bufobj %p should be %p",
1185		    bp, bp->b_bufobj, bo));
1186		if (bp->b_bufobj != bo) {	/* XXX: necessary ? */
1187			BUF_UNLOCK(bp);
1188			BO_LOCK(bo);
1189			return (EAGAIN);
1190		}
1191		/*
1192		 * XXX Since there are no node locks for NFS, I
1193		 * believe there is a slight chance that a delayed
1194		 * write will occur while sleeping just above, so
1195		 * check for it.
1196		 */
1197		if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1198		    (flags & V_SAVE)) {
1199			bremfree(bp);
1200			bp->b_flags |= B_ASYNC;
1201			bwrite(bp);
1202			BO_LOCK(bo);
1203			return (EAGAIN);	/* XXX: why not loop ? */
1204		}
1205		bremfree(bp);
1206		bp->b_flags |= (B_INVAL | B_RELBUF);
1207		bp->b_flags &= ~B_ASYNC;
1208		brelse(bp);
1209		BO_LOCK(bo);
1210		if (nbp != NULL &&
1211		    (nbp->b_bufobj != bo ||
1212		     nbp->b_lblkno != lblkno ||
1213		     (nbp->b_xflags &
1214		      (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1215			break;			/* nbp invalid */
1216	}
1217	return (retval);
1218}
1219
1220/*
1221 * Truncate a file's buffer and pages to a specified length.  This
1222 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1223 * sync activity.
1224 */
1225int
1226vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
1227    off_t length, int blksize)
1228{
1229	struct buf *bp, *nbp;
1230	int anyfreed;
1231	int trunclbn;
1232	struct bufobj *bo;
1233
1234	CTR2(KTR_VFS, "vtruncbuf vp %p length %jd", vp, length);
1235	/*
1236	 * Round up to the *next* lbn.
1237	 */
1238	trunclbn = (length + blksize - 1) / blksize;
1239
1240	ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1241restart:
1242	VI_LOCK(vp);
1243	bo = &vp->v_bufobj;
1244	anyfreed = 1;
1245	for (;anyfreed;) {
1246		anyfreed = 0;
1247		TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1248			if (bp->b_lblkno < trunclbn)
1249				continue;
1250			if (BUF_LOCK(bp,
1251			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1252			    VI_MTX(vp)) == ENOLCK)
1253				goto restart;
1254
1255			bremfree(bp);
1256			bp->b_flags |= (B_INVAL | B_RELBUF);
1257			bp->b_flags &= ~B_ASYNC;
1258			brelse(bp);
1259			anyfreed = 1;
1260
1261			if (nbp != NULL &&
1262			    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1263			    (nbp->b_vp != vp) ||
1264			    (nbp->b_flags & B_DELWRI))) {
1265				goto restart;
1266			}
1267			VI_LOCK(vp);
1268		}
1269
1270		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1271			if (bp->b_lblkno < trunclbn)
1272				continue;
1273			if (BUF_LOCK(bp,
1274			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1275			    VI_MTX(vp)) == ENOLCK)
1276				goto restart;
1277			bremfree(bp);
1278			bp->b_flags |= (B_INVAL | B_RELBUF);
1279			bp->b_flags &= ~B_ASYNC;
1280			brelse(bp);
1281			anyfreed = 1;
1282			if (nbp != NULL &&
1283			    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1284			    (nbp->b_vp != vp) ||
1285			    (nbp->b_flags & B_DELWRI) == 0)) {
1286				goto restart;
1287			}
1288			VI_LOCK(vp);
1289		}
1290	}
1291
1292	if (length > 0) {
1293restartsync:
1294		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1295			if (bp->b_lblkno > 0)
1296				continue;
1297			/*
1298			 * Since we hold the vnode lock this should only
1299			 * fail if we're racing with the buf daemon.
1300			 */
1301			if (BUF_LOCK(bp,
1302			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1303			    VI_MTX(vp)) == ENOLCK) {
1304				goto restart;
1305			}
1306			VNASSERT((bp->b_flags & B_DELWRI), vp,
1307			    ("buf(%p) on dirty queue without DELWRI", bp));
1308
1309			bremfree(bp);
1310			bawrite(bp);
1311			VI_LOCK(vp);
1312			goto restartsync;
1313		}
1314	}
1315
1316	bufobj_wwait(bo, 0, 0);
1317	VI_UNLOCK(vp);
1318	vnode_pager_setsize(vp, length);
1319
1320	return (0);
1321}
1322
1323/*
1324 * buf_splay() - splay tree core for the clean/dirty list of buffers in
1325 * 		 a vnode.
1326 *
1327 *	NOTE: We have to deal with the special case of a background bitmap
1328 *	buffer, a situation where two buffers will have the same logical
1329 *	block offset.  We want (1) only the foreground buffer to be accessed
1330 *	in a lookup and (2) must differentiate between the foreground and
1331 *	background buffer in the splay tree algorithm because the splay
1332 *	tree cannot normally handle multiple entities with the same 'index'.
1333 *	We accomplish this by adding differentiating flags to the splay tree's
1334 *	numerical domain.
1335 */
1336static
1337struct buf *
1338buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1339{
1340	struct buf dummy;
1341	struct buf *lefttreemax, *righttreemin, *y;
1342
1343	if (root == NULL)
1344		return (NULL);
1345	lefttreemax = righttreemin = &dummy;
1346	for (;;) {
1347		if (lblkno < root->b_lblkno ||
1348		    (lblkno == root->b_lblkno &&
1349		    (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1350			if ((y = root->b_left) == NULL)
1351				break;
1352			if (lblkno < y->b_lblkno) {
1353				/* Rotate right. */
1354				root->b_left = y->b_right;
1355				y->b_right = root;
1356				root = y;
1357				if ((y = root->b_left) == NULL)
1358					break;
1359			}
1360			/* Link into the new root's right tree. */
1361			righttreemin->b_left = root;
1362			righttreemin = root;
1363		} else if (lblkno > root->b_lblkno ||
1364		    (lblkno == root->b_lblkno &&
1365		    (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
1366			if ((y = root->b_right) == NULL)
1367				break;
1368			if (lblkno > y->b_lblkno) {
1369				/* Rotate left. */
1370				root->b_right = y->b_left;
1371				y->b_left = root;
1372				root = y;
1373				if ((y = root->b_right) == NULL)
1374					break;
1375			}
1376			/* Link into the new root's left tree. */
1377			lefttreemax->b_right = root;
1378			lefttreemax = root;
1379		} else {
1380			break;
1381		}
1382		root = y;
1383	}
1384	/* Assemble the new root. */
1385	lefttreemax->b_right = root->b_left;
1386	righttreemin->b_left = root->b_right;
1387	root->b_left = dummy.b_right;
1388	root->b_right = dummy.b_left;
1389	return (root);
1390}
1391
1392static void
1393buf_vlist_remove(struct buf *bp)
1394{
1395	struct buf *root;
1396	struct bufv *bv;
1397
1398	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1399	ASSERT_BO_LOCKED(bp->b_bufobj);
1400	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1401	    (BX_VNDIRTY|BX_VNCLEAN),
1402	    ("buf_vlist_remove: Buf %p is on two lists", bp));
1403	if (bp->b_xflags & BX_VNDIRTY)
1404		bv = &bp->b_bufobj->bo_dirty;
1405	else
1406		bv = &bp->b_bufobj->bo_clean;
1407	if (bp != bv->bv_root) {
1408		root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1409		KASSERT(root == bp, ("splay lookup failed in remove"));
1410	}
1411	if (bp->b_left == NULL) {
1412		root = bp->b_right;
1413	} else {
1414		root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1415		root->b_right = bp->b_right;
1416	}
1417	bv->bv_root = root;
1418	TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1419	bv->bv_cnt--;
1420	bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1421}
1422
1423/*
1424 * Add the buffer to the sorted clean or dirty block list using a
1425 * splay tree algorithm.
1426 *
1427 * NOTE: xflags is passed as a constant, optimizing this inline function!
1428 */
1429static void
1430buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1431{
1432	struct buf *root;
1433	struct bufv *bv;
1434
1435	ASSERT_BO_LOCKED(bo);
1436	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1437	    ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1438	bp->b_xflags |= xflags;
1439	if (xflags & BX_VNDIRTY)
1440		bv = &bo->bo_dirty;
1441	else
1442		bv = &bo->bo_clean;
1443
1444	root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1445	if (root == NULL) {
1446		bp->b_left = NULL;
1447		bp->b_right = NULL;
1448		TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1449	} else if (bp->b_lblkno < root->b_lblkno ||
1450	    (bp->b_lblkno == root->b_lblkno &&
1451	    (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1452		bp->b_left = root->b_left;
1453		bp->b_right = root;
1454		root->b_left = NULL;
1455		TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1456	} else {
1457		bp->b_right = root->b_right;
1458		bp->b_left = root;
1459		root->b_right = NULL;
1460		TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1461	}
1462	bv->bv_cnt++;
1463	bv->bv_root = bp;
1464}
1465
1466/*
1467 * Lookup a buffer using the splay tree.  Note that we specifically avoid
1468 * shadow buffers used in background bitmap writes.
1469 *
1470 * This code isn't quite efficient as it could be because we are maintaining
1471 * two sorted lists and do not know which list the block resides in.
1472 *
1473 * During a "make buildworld" the desired buffer is found at one of
1474 * the roots more than 60% of the time.  Thus, checking both roots
1475 * before performing either splay eliminates unnecessary splays on the
1476 * first tree splayed.
1477 */
1478struct buf *
1479gbincore(struct bufobj *bo, daddr_t lblkno)
1480{
1481	struct buf *bp;
1482
1483	ASSERT_BO_LOCKED(bo);
1484	if ((bp = bo->bo_clean.bv_root) != NULL &&
1485	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1486		return (bp);
1487	if ((bp = bo->bo_dirty.bv_root) != NULL &&
1488	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1489		return (bp);
1490	if ((bp = bo->bo_clean.bv_root) != NULL) {
1491		bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1492		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1493			return (bp);
1494	}
1495	if ((bp = bo->bo_dirty.bv_root) != NULL) {
1496		bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1497		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1498			return (bp);
1499	}
1500	return (NULL);
1501}
1502
1503/*
1504 * Associate a buffer with a vnode.
1505 */
1506void
1507bgetvp(struct vnode *vp, struct buf *bp)
1508{
1509
1510	VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1511
1512	CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1513	VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1514	    ("bgetvp: bp already attached! %p", bp));
1515
1516	ASSERT_VI_LOCKED(vp, "bgetvp");
1517	vholdl(vp);
1518	if (VFS_NEEDSGIANT(vp->v_mount) ||
1519	    vp->v_bufobj.bo_flag & BO_NEEDSGIANT)
1520		bp->b_flags |= B_NEEDSGIANT;
1521	bp->b_vp = vp;
1522	bp->b_bufobj = &vp->v_bufobj;
1523	/*
1524	 * Insert onto list for new vnode.
1525	 */
1526	buf_vlist_add(bp, &vp->v_bufobj, BX_VNCLEAN);
1527}
1528
1529/*
1530 * Disassociate a buffer from a vnode.
1531 */
1532void
1533brelvp(struct buf *bp)
1534{
1535	struct bufobj *bo;
1536	struct vnode *vp;
1537
1538	CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1539	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1540
1541	/*
1542	 * Delete from old vnode list, if on one.
1543	 */
1544	vp = bp->b_vp;		/* XXX */
1545	bo = bp->b_bufobj;
1546	BO_LOCK(bo);
1547	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1548		buf_vlist_remove(bp);
1549	else
1550		panic("brelvp: Buffer %p not on queue.", bp);
1551	if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1552		bo->bo_flag &= ~BO_ONWORKLST;
1553		mtx_lock(&sync_mtx);
1554		LIST_REMOVE(bo, bo_synclist);
1555		syncer_worklist_len--;
1556		mtx_unlock(&sync_mtx);
1557	}
1558	bp->b_flags &= ~B_NEEDSGIANT;
1559	bp->b_vp = NULL;
1560	bp->b_bufobj = NULL;
1561	vdropl(vp);
1562}
1563
1564/*
1565 * Add an item to the syncer work queue.
1566 */
1567static void
1568vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1569{
1570	int slot;
1571
1572	ASSERT_BO_LOCKED(bo);
1573
1574	mtx_lock(&sync_mtx);
1575	if (bo->bo_flag & BO_ONWORKLST)
1576		LIST_REMOVE(bo, bo_synclist);
1577	else {
1578		bo->bo_flag |= BO_ONWORKLST;
1579		syncer_worklist_len++;
1580	}
1581
1582	if (delay > syncer_maxdelay - 2)
1583		delay = syncer_maxdelay - 2;
1584	slot = (syncer_delayno + delay) & syncer_mask;
1585
1586	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], bo, bo_synclist);
1587	mtx_unlock(&sync_mtx);
1588}
1589
1590static int
1591sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1592{
1593	int error, len;
1594
1595	mtx_lock(&sync_mtx);
1596	len = syncer_worklist_len - sync_vnode_count;
1597	mtx_unlock(&sync_mtx);
1598	error = SYSCTL_OUT(req, &len, sizeof(len));
1599	return (error);
1600}
1601
1602SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1603    sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1604
1605static struct proc *updateproc;
1606static void sched_sync(void);
1607static struct kproc_desc up_kp = {
1608	"syncer",
1609	sched_sync,
1610	&updateproc
1611};
1612SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
1613
1614static int
1615sync_vnode(struct bufobj *bo, struct thread *td)
1616{
1617	struct vnode *vp;
1618	struct mount *mp;
1619
1620	vp = bo->__bo_vnode;	/* XXX */
1621	if (VOP_ISLOCKED(vp, NULL) != 0)
1622		return (1);
1623	if (VI_TRYLOCK(vp) == 0)
1624		return (1);
1625	/*
1626	 * We use vhold in case the vnode does not
1627	 * successfully sync.  vhold prevents the vnode from
1628	 * going away when we unlock the sync_mtx so that
1629	 * we can acquire the vnode interlock.
1630	 */
1631	vholdl(vp);
1632	mtx_unlock(&sync_mtx);
1633	VI_UNLOCK(vp);
1634	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1635		vdrop(vp);
1636		mtx_lock(&sync_mtx);
1637		return (1);
1638	}
1639	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1640	(void) VOP_FSYNC(vp, MNT_LAZY, td);
1641	VOP_UNLOCK(vp, 0, td);
1642	vn_finished_write(mp);
1643	VI_LOCK(vp);
1644	if ((bo->bo_flag & BO_ONWORKLST) != 0) {
1645		/*
1646		 * Put us back on the worklist.  The worklist
1647		 * routine will remove us from our current
1648		 * position and then add us back in at a later
1649		 * position.
1650		 */
1651		vn_syncer_add_to_worklist(bo, syncdelay);
1652	}
1653	vdropl(vp);
1654	mtx_lock(&sync_mtx);
1655	return (0);
1656}
1657
1658/*
1659 * System filesystem synchronizer daemon.
1660 */
1661static void
1662sched_sync(void)
1663{
1664	struct synclist *next;
1665	struct synclist *slp;
1666	struct bufobj *bo;
1667	long starttime;
1668	struct thread *td = FIRST_THREAD_IN_PROC(updateproc);
1669	static int dummychan;
1670	int last_work_seen;
1671	int net_worklist_len;
1672	int syncer_final_iter;
1673	int first_printf;
1674	int error;
1675
1676	mtx_lock(&Giant);
1677	last_work_seen = 0;
1678	syncer_final_iter = 0;
1679	first_printf = 1;
1680	syncer_state = SYNCER_RUNNING;
1681	starttime = time_uptime;
1682	td->td_pflags |= TDP_NORUNNINGBUF;
1683
1684	EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1685	    SHUTDOWN_PRI_LAST);
1686
1687	mtx_lock(&sync_mtx);
1688	for (;;) {
1689		if (syncer_state == SYNCER_FINAL_DELAY &&
1690		    syncer_final_iter == 0) {
1691			mtx_unlock(&sync_mtx);
1692			kthread_suspend_check(td->td_proc);
1693			mtx_lock(&sync_mtx);
1694		}
1695		net_worklist_len = syncer_worklist_len - sync_vnode_count;
1696		if (syncer_state != SYNCER_RUNNING &&
1697		    starttime != time_uptime) {
1698			if (first_printf) {
1699				printf("\nSyncing disks, vnodes remaining...");
1700				first_printf = 0;
1701			}
1702			printf("%d ", net_worklist_len);
1703		}
1704		starttime = time_uptime;
1705
1706		/*
1707		 * Push files whose dirty time has expired.  Be careful
1708		 * of interrupt race on slp queue.
1709		 *
1710		 * Skip over empty worklist slots when shutting down.
1711		 */
1712		do {
1713			slp = &syncer_workitem_pending[syncer_delayno];
1714			syncer_delayno += 1;
1715			if (syncer_delayno == syncer_maxdelay)
1716				syncer_delayno = 0;
1717			next = &syncer_workitem_pending[syncer_delayno];
1718			/*
1719			 * If the worklist has wrapped since the
1720			 * it was emptied of all but syncer vnodes,
1721			 * switch to the FINAL_DELAY state and run
1722			 * for one more second.
1723			 */
1724			if (syncer_state == SYNCER_SHUTTING_DOWN &&
1725			    net_worklist_len == 0 &&
1726			    last_work_seen == syncer_delayno) {
1727				syncer_state = SYNCER_FINAL_DELAY;
1728				syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1729			}
1730		} while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1731		    syncer_worklist_len > 0);
1732
1733		/*
1734		 * Keep track of the last time there was anything
1735		 * on the worklist other than syncer vnodes.
1736		 * Return to the SHUTTING_DOWN state if any
1737		 * new work appears.
1738		 */
1739		if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1740			last_work_seen = syncer_delayno;
1741		if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1742			syncer_state = SYNCER_SHUTTING_DOWN;
1743		while ((bo = LIST_FIRST(slp)) != NULL) {
1744			error = sync_vnode(bo, td);
1745			if (error == 1) {
1746				LIST_REMOVE(bo, bo_synclist);
1747				LIST_INSERT_HEAD(next, bo, bo_synclist);
1748				continue;
1749			}
1750		}
1751		if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1752			syncer_final_iter--;
1753		/*
1754		 * The variable rushjob allows the kernel to speed up the
1755		 * processing of the filesystem syncer process. A rushjob
1756		 * value of N tells the filesystem syncer to process the next
1757		 * N seconds worth of work on its queue ASAP. Currently rushjob
1758		 * is used by the soft update code to speed up the filesystem
1759		 * syncer process when the incore state is getting so far
1760		 * ahead of the disk that the kernel memory pool is being
1761		 * threatened with exhaustion.
1762		 */
1763		if (rushjob > 0) {
1764			rushjob -= 1;
1765			continue;
1766		}
1767		/*
1768		 * Just sleep for a short period of time between
1769		 * iterations when shutting down to allow some I/O
1770		 * to happen.
1771		 *
1772		 * If it has taken us less than a second to process the
1773		 * current work, then wait. Otherwise start right over
1774		 * again. We can still lose time if any single round
1775		 * takes more than two seconds, but it does not really
1776		 * matter as we are just trying to generally pace the
1777		 * filesystem activity.
1778		 */
1779		if (syncer_state != SYNCER_RUNNING)
1780			msleep(&dummychan, &sync_mtx, PPAUSE, "syncfnl",
1781			    hz / SYNCER_SHUTDOWN_SPEEDUP);
1782		else if (time_uptime == starttime)
1783			msleep(&lbolt, &sync_mtx, PPAUSE, "syncer", 0);
1784	}
1785}
1786
1787/*
1788 * Request the syncer daemon to speed up its work.
1789 * We never push it to speed up more than half of its
1790 * normal turn time, otherwise it could take over the cpu.
1791 */
1792int
1793speedup_syncer(void)
1794{
1795	struct thread *td;
1796	int ret = 0;
1797
1798	td = FIRST_THREAD_IN_PROC(updateproc);
1799	sleepq_remove(td, &lbolt);
1800	mtx_lock(&sync_mtx);
1801	if (rushjob < syncdelay / 2) {
1802		rushjob += 1;
1803		stat_rush_requests += 1;
1804		ret = 1;
1805	}
1806	mtx_unlock(&sync_mtx);
1807	return (ret);
1808}
1809
1810/*
1811 * Tell the syncer to speed up its work and run though its work
1812 * list several times, then tell it to shut down.
1813 */
1814static void
1815syncer_shutdown(void *arg, int howto)
1816{
1817	struct thread *td;
1818
1819	if (howto & RB_NOSYNC)
1820		return;
1821	td = FIRST_THREAD_IN_PROC(updateproc);
1822	sleepq_remove(td, &lbolt);
1823	mtx_lock(&sync_mtx);
1824	syncer_state = SYNCER_SHUTTING_DOWN;
1825	rushjob = 0;
1826	mtx_unlock(&sync_mtx);
1827	kproc_shutdown(arg, howto);
1828}
1829
1830/*
1831 * Reassign a buffer from one vnode to another.
1832 * Used to assign file specific control information
1833 * (indirect blocks) to the vnode to which they belong.
1834 */
1835void
1836reassignbuf(struct buf *bp)
1837{
1838	struct vnode *vp;
1839	struct bufobj *bo;
1840	int delay;
1841#ifdef INVARIANTS
1842	struct bufv *bv;
1843#endif
1844
1845	vp = bp->b_vp;
1846	bo = bp->b_bufobj;
1847	++reassignbufcalls;
1848
1849	CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1850	    bp, bp->b_vp, bp->b_flags);
1851	/*
1852	 * B_PAGING flagged buffers cannot be reassigned because their vp
1853	 * is not fully linked in.
1854	 */
1855	if (bp->b_flags & B_PAGING)
1856		panic("cannot reassign paging buffer");
1857
1858	/*
1859	 * Delete from old vnode list, if on one.
1860	 */
1861	VI_LOCK(vp);
1862	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1863		buf_vlist_remove(bp);
1864	else
1865		panic("reassignbuf: Buffer %p not on queue.", bp);
1866	/*
1867	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1868	 * of clean buffers.
1869	 */
1870	if (bp->b_flags & B_DELWRI) {
1871		if ((bo->bo_flag & BO_ONWORKLST) == 0) {
1872			switch (vp->v_type) {
1873			case VDIR:
1874				delay = dirdelay;
1875				break;
1876			case VCHR:
1877				delay = metadelay;
1878				break;
1879			default:
1880				delay = filedelay;
1881			}
1882			vn_syncer_add_to_worklist(bo, delay);
1883		}
1884		buf_vlist_add(bp, bo, BX_VNDIRTY);
1885	} else {
1886		buf_vlist_add(bp, bo, BX_VNCLEAN);
1887
1888		if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1889			mtx_lock(&sync_mtx);
1890			LIST_REMOVE(bo, bo_synclist);
1891			syncer_worklist_len--;
1892			mtx_unlock(&sync_mtx);
1893			bo->bo_flag &= ~BO_ONWORKLST;
1894		}
1895	}
1896#ifdef INVARIANTS
1897	bv = &bo->bo_clean;
1898	bp = TAILQ_FIRST(&bv->bv_hd);
1899	KASSERT(bp == NULL || bp->b_bufobj == bo,
1900	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1901	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1902	KASSERT(bp == NULL || bp->b_bufobj == bo,
1903	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1904	bv = &bo->bo_dirty;
1905	bp = TAILQ_FIRST(&bv->bv_hd);
1906	KASSERT(bp == NULL || bp->b_bufobj == bo,
1907	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1908	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1909	KASSERT(bp == NULL || bp->b_bufobj == bo,
1910	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1911#endif
1912	VI_UNLOCK(vp);
1913}
1914
1915/*
1916 * Increment the use and hold counts on the vnode, taking care to reference
1917 * the driver's usecount if this is a chardev.  The vholdl() will remove
1918 * the vnode from the free list if it is presently free.  Requires the
1919 * vnode interlock and returns with it held.
1920 */
1921static void
1922v_incr_usecount(struct vnode *vp)
1923{
1924
1925	CTR3(KTR_VFS, "v_incr_usecount: vp %p holdcnt %d usecount %d\n",
1926	    vp, vp->v_holdcnt, vp->v_usecount);
1927	vp->v_usecount++;
1928	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1929		dev_lock();
1930		vp->v_rdev->si_usecount++;
1931		dev_unlock();
1932	}
1933	vholdl(vp);
1934}
1935
1936/*
1937 * Turn a holdcnt into a use+holdcnt such that only one call to
1938 * v_decr_usecount is needed.
1939 */
1940static void
1941v_upgrade_usecount(struct vnode *vp)
1942{
1943
1944	CTR3(KTR_VFS, "v_upgrade_usecount: vp %p holdcnt %d usecount %d\n",
1945	    vp, vp->v_holdcnt, vp->v_usecount);
1946	vp->v_usecount++;
1947	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1948		dev_lock();
1949		vp->v_rdev->si_usecount++;
1950		dev_unlock();
1951	}
1952}
1953
1954/*
1955 * Decrement the vnode use and hold count along with the driver's usecount
1956 * if this is a chardev.  The vdropl() below releases the vnode interlock
1957 * as it may free the vnode.
1958 */
1959static void
1960v_decr_usecount(struct vnode *vp)
1961{
1962
1963	CTR3(KTR_VFS, "v_decr_usecount: vp %p holdcnt %d usecount %d\n",
1964	    vp, vp->v_holdcnt, vp->v_usecount);
1965	ASSERT_VI_LOCKED(vp, __FUNCTION__);
1966	VNASSERT(vp->v_usecount > 0, vp,
1967	    ("v_decr_usecount: negative usecount"));
1968	vp->v_usecount--;
1969	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1970		dev_lock();
1971		vp->v_rdev->si_usecount--;
1972		dev_unlock();
1973	}
1974	vdropl(vp);
1975}
1976
1977/*
1978 * Decrement only the use count and driver use count.  This is intended to
1979 * be paired with a follow on vdropl() to release the remaining hold count.
1980 * In this way we may vgone() a vnode with a 0 usecount without risk of
1981 * having it end up on a free list because the hold count is kept above 0.
1982 */
1983static void
1984v_decr_useonly(struct vnode *vp)
1985{
1986
1987	CTR3(KTR_VFS, "v_decr_useonly: vp %p holdcnt %d usecount %d\n",
1988	    vp, vp->v_holdcnt, vp->v_usecount);
1989	ASSERT_VI_LOCKED(vp, __FUNCTION__);
1990	VNASSERT(vp->v_usecount > 0, vp,
1991	    ("v_decr_useonly: negative usecount"));
1992	vp->v_usecount--;
1993	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1994		dev_lock();
1995		vp->v_rdev->si_usecount--;
1996		dev_unlock();
1997	}
1998}
1999
2000/*
2001 * Grab a particular vnode from the free list, increment its
2002 * reference count and lock it. The vnode lock bit is set if the
2003 * vnode is being eliminated in vgone. The process is awakened
2004 * when the transition is completed, and an error returned to
2005 * indicate that the vnode is no longer usable (possibly having
2006 * been changed to a new filesystem type).
2007 */
2008int
2009vget(struct vnode *vp, int flags, struct thread *td)
2010{
2011	int oweinact;
2012	int oldflags;
2013	int error;
2014
2015	error = 0;
2016	oldflags = flags;
2017	oweinact = 0;
2018	VFS_ASSERT_GIANT(vp->v_mount);
2019	if ((flags & LK_INTERLOCK) == 0)
2020		VI_LOCK(vp);
2021	/*
2022	 * If the inactive call was deferred because vput() was called
2023	 * with a shared lock, we have to do it here before another thread
2024	 * gets a reference to data that should be dead.
2025	 */
2026	if (vp->v_iflag & VI_OWEINACT) {
2027		if (flags & LK_NOWAIT) {
2028			VI_UNLOCK(vp);
2029			return (EBUSY);
2030		}
2031		flags &= ~LK_TYPE_MASK;
2032		flags |= LK_EXCLUSIVE;
2033		oweinact = 1;
2034	}
2035	vholdl(vp);
2036	if ((error = vn_lock(vp, flags | LK_INTERLOCK, td)) != 0) {
2037		vdrop(vp);
2038		return (error);
2039	}
2040	VI_LOCK(vp);
2041	/* Upgrade our holdcnt to a usecount. */
2042	v_upgrade_usecount(vp);
2043	if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2044		panic("vget: vn_lock failed to return ENOENT\n");
2045	if (oweinact) {
2046		if (vp->v_iflag & VI_OWEINACT)
2047			vinactive(vp, td);
2048		VI_UNLOCK(vp);
2049		if ((oldflags & LK_TYPE_MASK) == 0)
2050			VOP_UNLOCK(vp, 0, td);
2051	} else
2052		VI_UNLOCK(vp);
2053	return (0);
2054}
2055
2056/*
2057 * Increase the reference count of a vnode.
2058 */
2059void
2060vref(struct vnode *vp)
2061{
2062
2063	VI_LOCK(vp);
2064	v_incr_usecount(vp);
2065	VI_UNLOCK(vp);
2066}
2067
2068/*
2069 * Return reference count of a vnode.
2070 *
2071 * The results of this call are only guaranteed when some mechanism other
2072 * than the VI lock is used to stop other processes from gaining references
2073 * to the vnode.  This may be the case if the caller holds the only reference.
2074 * This is also useful when stale data is acceptable as race conditions may
2075 * be accounted for by some other means.
2076 */
2077int
2078vrefcnt(struct vnode *vp)
2079{
2080	int usecnt;
2081
2082	VI_LOCK(vp);
2083	usecnt = vp->v_usecount;
2084	VI_UNLOCK(vp);
2085
2086	return (usecnt);
2087}
2088
2089
2090/*
2091 * Vnode put/release.
2092 * If count drops to zero, call inactive routine and return to freelist.
2093 */
2094void
2095vrele(struct vnode *vp)
2096{
2097	struct thread *td = curthread;	/* XXX */
2098
2099	KASSERT(vp != NULL, ("vrele: null vp"));
2100	VFS_ASSERT_GIANT(vp->v_mount);
2101
2102	VI_LOCK(vp);
2103
2104	/* Skip this v_writecount check if we're going to panic below. */
2105	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2106	    ("vrele: missed vn_close"));
2107
2108	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2109	    vp->v_usecount == 1)) {
2110		v_decr_usecount(vp);
2111		return;
2112	}
2113	if (vp->v_usecount != 1) {
2114#ifdef DIAGNOSTIC
2115		vprint("vrele: negative ref count", vp);
2116#endif
2117		VI_UNLOCK(vp);
2118		panic("vrele: negative ref cnt");
2119	}
2120	/*
2121	 * We want to hold the vnode until the inactive finishes to
2122	 * prevent vgone() races.  We drop the use count here and the
2123	 * hold count below when we're done.
2124	 */
2125	v_decr_useonly(vp);
2126	/*
2127	 * We must call VOP_INACTIVE with the node locked. Mark
2128	 * as VI_DOINGINACT to avoid recursion.
2129	 */
2130	vp->v_iflag |= VI_OWEINACT;
2131	if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, td) == 0) {
2132		VI_LOCK(vp);
2133		if (vp->v_usecount > 0)
2134			vp->v_iflag &= ~VI_OWEINACT;
2135		if (vp->v_iflag & VI_OWEINACT)
2136			vinactive(vp, td);
2137		VOP_UNLOCK(vp, 0, td);
2138	} else {
2139		VI_LOCK(vp);
2140		if (vp->v_usecount > 0)
2141			vp->v_iflag &= ~VI_OWEINACT;
2142	}
2143	vdropl(vp);
2144}
2145
2146/*
2147 * Release an already locked vnode.  This give the same effects as
2148 * unlock+vrele(), but takes less time and avoids releasing and
2149 * re-aquiring the lock (as vrele() aquires the lock internally.)
2150 */
2151void
2152vput(struct vnode *vp)
2153{
2154	struct thread *td = curthread;	/* XXX */
2155	int error;
2156
2157	KASSERT(vp != NULL, ("vput: null vp"));
2158	ASSERT_VOP_LOCKED(vp, "vput");
2159	VFS_ASSERT_GIANT(vp->v_mount);
2160	VI_LOCK(vp);
2161	/* Skip this v_writecount check if we're going to panic below. */
2162	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2163	    ("vput: missed vn_close"));
2164	error = 0;
2165
2166	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2167	    vp->v_usecount == 1)) {
2168		VOP_UNLOCK(vp, 0, td);
2169		v_decr_usecount(vp);
2170		return;
2171	}
2172
2173	if (vp->v_usecount != 1) {
2174#ifdef DIAGNOSTIC
2175		vprint("vput: negative ref count", vp);
2176#endif
2177		panic("vput: negative ref cnt");
2178	}
2179	/*
2180	 * We want to hold the vnode until the inactive finishes to
2181	 * prevent vgone() races.  We drop the use count here and the
2182	 * hold count below when we're done.
2183	 */
2184	v_decr_useonly(vp);
2185	vp->v_iflag |= VI_OWEINACT;
2186	if (VOP_ISLOCKED(vp, NULL) != LK_EXCLUSIVE) {
2187		error = VOP_LOCK(vp, LK_EXCLUPGRADE|LK_INTERLOCK|LK_NOWAIT, td);
2188		VI_LOCK(vp);
2189		if (error) {
2190			if (vp->v_usecount > 0)
2191				vp->v_iflag &= ~VI_OWEINACT;
2192			goto done;
2193		}
2194	}
2195	if (vp->v_usecount > 0)
2196		vp->v_iflag &= ~VI_OWEINACT;
2197	if (vp->v_iflag & VI_OWEINACT)
2198		vinactive(vp, td);
2199	VOP_UNLOCK(vp, 0, td);
2200done:
2201	vdropl(vp);
2202}
2203
2204/*
2205 * Somebody doesn't want the vnode recycled.
2206 */
2207void
2208vhold(struct vnode *vp)
2209{
2210
2211	VI_LOCK(vp);
2212	vholdl(vp);
2213	VI_UNLOCK(vp);
2214}
2215
2216void
2217vholdl(struct vnode *vp)
2218{
2219
2220	vp->v_holdcnt++;
2221	if (VSHOULDBUSY(vp))
2222		vbusy(vp);
2223}
2224
2225/*
2226 * Note that there is one less who cares about this vnode.  vdrop() is the
2227 * opposite of vhold().
2228 */
2229void
2230vdrop(struct vnode *vp)
2231{
2232
2233	VI_LOCK(vp);
2234	vdropl(vp);
2235}
2236
2237/*
2238 * Drop the hold count of the vnode.  If this is the last reference to
2239 * the vnode we will free it if it has been vgone'd otherwise it is
2240 * placed on the free list.
2241 */
2242void
2243vdropl(struct vnode *vp)
2244{
2245
2246	ASSERT_VI_LOCKED(vp, "vdropl");
2247	if (vp->v_holdcnt <= 0)
2248		panic("vdrop: holdcnt %d", vp->v_holdcnt);
2249	vp->v_holdcnt--;
2250	if (vp->v_holdcnt == 0) {
2251		if (vp->v_iflag & VI_DOOMED) {
2252			vdestroy(vp);
2253			return;
2254		} else
2255			vfree(vp);
2256	}
2257	VI_UNLOCK(vp);
2258}
2259
2260/*
2261 * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2262 * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
2263 * OWEINACT tracks whether a vnode missed a call to inactive due to a
2264 * failed lock upgrade.
2265 */
2266static void
2267vinactive(struct vnode *vp, struct thread *td)
2268{
2269
2270	ASSERT_VOP_LOCKED(vp, "vinactive");
2271	ASSERT_VI_LOCKED(vp, "vinactive");
2272	VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2273	    ("vinactive: recursed on VI_DOINGINACT"));
2274	vp->v_iflag |= VI_DOINGINACT;
2275	vp->v_iflag &= ~VI_OWEINACT;
2276	VI_UNLOCK(vp);
2277	VOP_INACTIVE(vp, td);
2278	VI_LOCK(vp);
2279	VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2280	    ("vinactive: lost VI_DOINGINACT"));
2281	vp->v_iflag &= ~VI_DOINGINACT;
2282}
2283
2284/*
2285 * Remove any vnodes in the vnode table belonging to mount point mp.
2286 *
2287 * If FORCECLOSE is not specified, there should not be any active ones,
2288 * return error if any are found (nb: this is a user error, not a
2289 * system error). If FORCECLOSE is specified, detach any active vnodes
2290 * that are found.
2291 *
2292 * If WRITECLOSE is set, only flush out regular file vnodes open for
2293 * writing.
2294 *
2295 * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2296 *
2297 * `rootrefs' specifies the base reference count for the root vnode
2298 * of this filesystem. The root vnode is considered busy if its
2299 * v_usecount exceeds this value. On a successful return, vflush(, td)
2300 * will call vrele() on the root vnode exactly rootrefs times.
2301 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2302 * be zero.
2303 */
2304#ifdef DIAGNOSTIC
2305static int busyprt = 0;		/* print out busy vnodes */
2306SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
2307#endif
2308
2309int
2310vflush( struct mount *mp, int rootrefs, int flags, struct thread *td)
2311{
2312	struct vnode *vp, *mvp, *rootvp = NULL;
2313	struct vattr vattr;
2314	int busy = 0, error;
2315
2316	CTR1(KTR_VFS, "vflush: mp %p", mp);
2317	if (rootrefs > 0) {
2318		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2319		    ("vflush: bad args"));
2320		/*
2321		 * Get the filesystem root vnode. We can vput() it
2322		 * immediately, since with rootrefs > 0, it won't go away.
2323		 */
2324		if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp, td)) != 0)
2325			return (error);
2326		vput(rootvp);
2327
2328	}
2329	MNT_ILOCK(mp);
2330loop:
2331	MNT_VNODE_FOREACH(vp, mp, mvp) {
2332
2333		VI_LOCK(vp);
2334		vholdl(vp);
2335		MNT_IUNLOCK(mp);
2336		error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE, td);
2337		if (error) {
2338			vdrop(vp);
2339			MNT_ILOCK(mp);
2340			MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);
2341			goto loop;
2342		}
2343		/*
2344		 * Skip over a vnodes marked VV_SYSTEM.
2345		 */
2346		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2347			VOP_UNLOCK(vp, 0, td);
2348			vdrop(vp);
2349			MNT_ILOCK(mp);
2350			continue;
2351		}
2352		/*
2353		 * If WRITECLOSE is set, flush out unlinked but still open
2354		 * files (even if open only for reading) and regular file
2355		 * vnodes open for writing.
2356		 */
2357		if (flags & WRITECLOSE) {
2358			error = VOP_GETATTR(vp, &vattr, td->td_ucred, td);
2359			VI_LOCK(vp);
2360
2361			if ((vp->v_type == VNON ||
2362			    (error == 0 && vattr.va_nlink > 0)) &&
2363			    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2364				VOP_UNLOCK(vp, 0, td);
2365				vdropl(vp);
2366				MNT_ILOCK(mp);
2367				continue;
2368			}
2369		} else
2370			VI_LOCK(vp);
2371		/*
2372		 * With v_usecount == 0, all we need to do is clear out the
2373		 * vnode data structures and we are done.
2374		 *
2375		 * If FORCECLOSE is set, forcibly close the vnode.
2376		 */
2377		if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2378			VNASSERT(vp->v_usecount == 0 ||
2379			    (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2380			    ("device VNODE %p is FORCECLOSED", vp));
2381			vgonel(vp);
2382		} else {
2383			busy++;
2384#ifdef DIAGNOSTIC
2385			if (busyprt)
2386				vprint("vflush: busy vnode", vp);
2387#endif
2388		}
2389		VOP_UNLOCK(vp, 0, td);
2390		vdropl(vp);
2391		MNT_ILOCK(mp);
2392	}
2393	MNT_IUNLOCK(mp);
2394	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2395		/*
2396		 * If just the root vnode is busy, and if its refcount
2397		 * is equal to `rootrefs', then go ahead and kill it.
2398		 */
2399		VI_LOCK(rootvp);
2400		KASSERT(busy > 0, ("vflush: not busy"));
2401		VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2402		    ("vflush: usecount %d < rootrefs %d",
2403		     rootvp->v_usecount, rootrefs));
2404		if (busy == 1 && rootvp->v_usecount == rootrefs) {
2405			VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK, td);
2406			vgone(rootvp);
2407			VOP_UNLOCK(rootvp, 0, td);
2408			busy = 0;
2409		} else
2410			VI_UNLOCK(rootvp);
2411	}
2412	if (busy)
2413		return (EBUSY);
2414	for (; rootrefs > 0; rootrefs--)
2415		vrele(rootvp);
2416	return (0);
2417}
2418
2419/*
2420 * Recycle an unused vnode to the front of the free list.
2421 */
2422int
2423vrecycle(struct vnode *vp, struct thread *td)
2424{
2425	int recycled;
2426
2427	ASSERT_VOP_LOCKED(vp, "vrecycle");
2428	recycled = 0;
2429	VI_LOCK(vp);
2430	if (vp->v_usecount == 0) {
2431		recycled = 1;
2432		vgonel(vp);
2433	}
2434	VI_UNLOCK(vp);
2435	return (recycled);
2436}
2437
2438/*
2439 * Eliminate all activity associated with a vnode
2440 * in preparation for reuse.
2441 */
2442void
2443vgone(struct vnode *vp)
2444{
2445	VI_LOCK(vp);
2446	vgonel(vp);
2447	VI_UNLOCK(vp);
2448}
2449
2450/*
2451 * vgone, with the vp interlock held.
2452 */
2453void
2454vgonel(struct vnode *vp)
2455{
2456	struct thread *td;
2457	int oweinact;
2458	int active;
2459	struct mount *mp;
2460
2461	CTR1(KTR_VFS, "vgonel: vp %p", vp);
2462	ASSERT_VOP_LOCKED(vp, "vgonel");
2463	ASSERT_VI_LOCKED(vp, "vgonel");
2464	VNASSERT(vp->v_holdcnt, vp,
2465	    ("vgonel: vp %p has no reference.", vp));
2466	td = curthread;
2467
2468	/*
2469	 * Don't vgonel if we're already doomed.
2470	 */
2471	if (vp->v_iflag & VI_DOOMED)
2472		return;
2473	vp->v_iflag |= VI_DOOMED;
2474	/*
2475	 * Check to see if the vnode is in use.  If so, we have to call
2476	 * VOP_CLOSE() and VOP_INACTIVE().
2477	 */
2478	active = vp->v_usecount;
2479	oweinact = (vp->v_iflag & VI_OWEINACT);
2480	VI_UNLOCK(vp);
2481	/*
2482	 * Clean out any buffers associated with the vnode.
2483	 * If the flush fails, just toss the buffers.
2484	 */
2485	mp = NULL;
2486	if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2487		(void) vn_start_secondary_write(vp, &mp, V_WAIT);
2488	if (vinvalbuf(vp, V_SAVE, td, 0, 0) != 0)
2489		vinvalbuf(vp, 0, td, 0, 0);
2490
2491	/*
2492	 * If purging an active vnode, it must be closed and
2493	 * deactivated before being reclaimed.
2494	 */
2495	if (active)
2496		VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2497	if (oweinact || active) {
2498		VI_LOCK(vp);
2499		if ((vp->v_iflag & VI_DOINGINACT) == 0)
2500			vinactive(vp, td);
2501		VI_UNLOCK(vp);
2502	}
2503	/*
2504	 * Reclaim the vnode.
2505	 */
2506	if (VOP_RECLAIM(vp, td))
2507		panic("vgone: cannot reclaim");
2508	if (mp != NULL)
2509		vn_finished_secondary_write(mp);
2510	VNASSERT(vp->v_object == NULL, vp,
2511	    ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2512	/*
2513	 * Delete from old mount point vnode list.
2514	 */
2515	delmntque(vp);
2516	cache_purge(vp);
2517	/*
2518	 * Done with purge, reset to the standard lock and invalidate
2519	 * the vnode.
2520	 */
2521	VI_LOCK(vp);
2522	vp->v_vnlock = &vp->v_lock;
2523	vp->v_op = &dead_vnodeops;
2524	vp->v_tag = "none";
2525	vp->v_type = VBAD;
2526}
2527
2528/*
2529 * Calculate the total number of references to a special device.
2530 */
2531int
2532vcount(struct vnode *vp)
2533{
2534	int count;
2535
2536	dev_lock();
2537	count = vp->v_rdev->si_usecount;
2538	dev_unlock();
2539	return (count);
2540}
2541
2542/*
2543 * Same as above, but using the struct cdev *as argument
2544 */
2545int
2546count_dev(struct cdev *dev)
2547{
2548	int count;
2549
2550	dev_lock();
2551	count = dev->si_usecount;
2552	dev_unlock();
2553	return(count);
2554}
2555
2556/*
2557 * Print out a description of a vnode.
2558 */
2559static char *typename[] =
2560{"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2561 "VMARKER"};
2562
2563void
2564vn_printf(struct vnode *vp, const char *fmt, ...)
2565{
2566	va_list ap;
2567	char buf[96];
2568
2569	va_start(ap, fmt);
2570	vprintf(fmt, ap);
2571	va_end(ap);
2572	printf("%p: ", (void *)vp);
2573	printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2574	printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
2575	    vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2576	buf[0] = '\0';
2577	buf[1] = '\0';
2578	if (vp->v_vflag & VV_ROOT)
2579		strcat(buf, "|VV_ROOT");
2580	if (vp->v_vflag & VV_TEXT)
2581		strcat(buf, "|VV_TEXT");
2582	if (vp->v_vflag & VV_SYSTEM)
2583		strcat(buf, "|VV_SYSTEM");
2584	if (vp->v_vflag & VV_DELETED)
2585		strcat(buf, "|VV_DELETED");
2586	if (vp->v_iflag & VI_DOOMED)
2587		strcat(buf, "|VI_DOOMED");
2588	if (vp->v_iflag & VI_FREE)
2589		strcat(buf, "|VI_FREE");
2590	printf("    flags (%s)\n", buf + 1);
2591	if (mtx_owned(VI_MTX(vp)))
2592		printf(" VI_LOCKed");
2593	if (vp->v_object != NULL)
2594		printf("    v_object %p ref %d pages %d\n",
2595		    vp->v_object, vp->v_object->ref_count,
2596		    vp->v_object->resident_page_count);
2597	printf("    ");
2598	lockmgr_printinfo(vp->v_vnlock);
2599	printf("\n");
2600	if (vp->v_data != NULL)
2601		VOP_PRINT(vp);
2602}
2603
2604#ifdef DDB
2605/*
2606 * List all of the locked vnodes in the system.
2607 * Called when debugging the kernel.
2608 */
2609DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2610{
2611	struct mount *mp, *nmp;
2612	struct vnode *vp;
2613
2614	/*
2615	 * Note: because this is DDB, we can't obey the locking semantics
2616	 * for these structures, which means we could catch an inconsistent
2617	 * state and dereference a nasty pointer.  Not much to be done
2618	 * about that.
2619	 */
2620	printf("Locked vnodes\n");
2621	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2622		nmp = TAILQ_NEXT(mp, mnt_list);
2623		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2624			if (vp->v_type != VMARKER && VOP_ISLOCKED(vp, NULL))
2625				vprint("", vp);
2626		}
2627		nmp = TAILQ_NEXT(mp, mnt_list);
2628	}
2629}
2630
2631/*
2632 * Show details about the given vnode.
2633 */
2634DB_SHOW_COMMAND(vnode, db_show_vnode)
2635{
2636	struct vnode *vp;
2637
2638	if (!have_addr)
2639		return;
2640	vp = (struct vnode *)addr;
2641	vn_printf(vp, "vnode ");
2642}
2643#endif	/* DDB */
2644
2645/*
2646 * Fill in a struct xvfsconf based on a struct vfsconf.
2647 */
2648static void
2649vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
2650{
2651
2652	strcpy(xvfsp->vfc_name, vfsp->vfc_name);
2653	xvfsp->vfc_typenum = vfsp->vfc_typenum;
2654	xvfsp->vfc_refcount = vfsp->vfc_refcount;
2655	xvfsp->vfc_flags = vfsp->vfc_flags;
2656	/*
2657	 * These are unused in userland, we keep them
2658	 * to not break binary compatibility.
2659	 */
2660	xvfsp->vfc_vfsops = NULL;
2661	xvfsp->vfc_next = NULL;
2662}
2663
2664/*
2665 * Top level filesystem related information gathering.
2666 */
2667static int
2668sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
2669{
2670	struct vfsconf *vfsp;
2671	struct xvfsconf xvfsp;
2672	int error;
2673
2674	error = 0;
2675	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2676		bzero(&xvfsp, sizeof(xvfsp));
2677		vfsconf2x(vfsp, &xvfsp);
2678		error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
2679		if (error)
2680			break;
2681	}
2682	return (error);
2683}
2684
2685SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLFLAG_RD, NULL, 0, sysctl_vfs_conflist,
2686    "S,xvfsconf", "List of all configured filesystems");
2687
2688#ifndef BURN_BRIDGES
2689static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
2690
2691static int
2692vfs_sysctl(SYSCTL_HANDLER_ARGS)
2693{
2694	int *name = (int *)arg1 - 1;	/* XXX */
2695	u_int namelen = arg2 + 1;	/* XXX */
2696	struct vfsconf *vfsp;
2697	struct xvfsconf xvfsp;
2698
2699	printf("WARNING: userland calling deprecated sysctl, "
2700	    "please rebuild world\n");
2701
2702#if 1 || defined(COMPAT_PRELITE2)
2703	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2704	if (namelen == 1)
2705		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2706#endif
2707
2708	switch (name[1]) {
2709	case VFS_MAXTYPENUM:
2710		if (namelen != 2)
2711			return (ENOTDIR);
2712		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2713	case VFS_CONF:
2714		if (namelen != 3)
2715			return (ENOTDIR);	/* overloaded */
2716		TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
2717			if (vfsp->vfc_typenum == name[2])
2718				break;
2719		if (vfsp == NULL)
2720			return (EOPNOTSUPP);
2721		bzero(&xvfsp, sizeof(xvfsp));
2722		vfsconf2x(vfsp, &xvfsp);
2723		return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
2724	}
2725	return (EOPNOTSUPP);
2726}
2727
2728static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
2729	vfs_sysctl, "Generic filesystem");
2730
2731#if 1 || defined(COMPAT_PRELITE2)
2732
2733static int
2734sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2735{
2736	int error;
2737	struct vfsconf *vfsp;
2738	struct ovfsconf ovfs;
2739
2740	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2741		bzero(&ovfs, sizeof(ovfs));
2742		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2743		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2744		ovfs.vfc_index = vfsp->vfc_typenum;
2745		ovfs.vfc_refcount = vfsp->vfc_refcount;
2746		ovfs.vfc_flags = vfsp->vfc_flags;
2747		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2748		if (error)
2749			return error;
2750	}
2751	return 0;
2752}
2753
2754#endif /* 1 || COMPAT_PRELITE2 */
2755#endif /* !BURN_BRIDGES */
2756
2757#define KINFO_VNODESLOP		10
2758#ifdef notyet
2759/*
2760 * Dump vnode list (via sysctl).
2761 */
2762/* ARGSUSED */
2763static int
2764sysctl_vnode(SYSCTL_HANDLER_ARGS)
2765{
2766	struct xvnode *xvn;
2767	struct thread *td = req->td;
2768	struct mount *mp;
2769	struct vnode *vp;
2770	int error, len, n;
2771
2772	/*
2773	 * Stale numvnodes access is not fatal here.
2774	 */
2775	req->lock = 0;
2776	len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
2777	if (!req->oldptr)
2778		/* Make an estimate */
2779		return (SYSCTL_OUT(req, 0, len));
2780
2781	error = sysctl_wire_old_buffer(req, 0);
2782	if (error != 0)
2783		return (error);
2784	xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
2785	n = 0;
2786	mtx_lock(&mountlist_mtx);
2787	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2788		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td))
2789			continue;
2790		MNT_ILOCK(mp);
2791		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2792			if (n == len)
2793				break;
2794			vref(vp);
2795			xvn[n].xv_size = sizeof *xvn;
2796			xvn[n].xv_vnode = vp;
2797			xvn[n].xv_id = 0;	/* XXX compat */
2798#define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
2799			XV_COPY(usecount);
2800			XV_COPY(writecount);
2801			XV_COPY(holdcnt);
2802			XV_COPY(mount);
2803			XV_COPY(numoutput);
2804			XV_COPY(type);
2805#undef XV_COPY
2806			xvn[n].xv_flag = vp->v_vflag;
2807
2808			switch (vp->v_type) {
2809			case VREG:
2810			case VDIR:
2811			case VLNK:
2812				break;
2813			case VBLK:
2814			case VCHR:
2815				if (vp->v_rdev == NULL) {
2816					vrele(vp);
2817					continue;
2818				}
2819				xvn[n].xv_dev = dev2udev(vp->v_rdev);
2820				break;
2821			case VSOCK:
2822				xvn[n].xv_socket = vp->v_socket;
2823				break;
2824			case VFIFO:
2825				xvn[n].xv_fifo = vp->v_fifoinfo;
2826				break;
2827			case VNON:
2828			case VBAD:
2829			default:
2830				/* shouldn't happen? */
2831				vrele(vp);
2832				continue;
2833			}
2834			vrele(vp);
2835			++n;
2836		}
2837		MNT_IUNLOCK(mp);
2838		mtx_lock(&mountlist_mtx);
2839		vfs_unbusy(mp, td);
2840		if (n == len)
2841			break;
2842	}
2843	mtx_unlock(&mountlist_mtx);
2844
2845	error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
2846	free(xvn, M_TEMP);
2847	return (error);
2848}
2849
2850SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2851	0, 0, sysctl_vnode, "S,xvnode", "");
2852#endif
2853
2854/*
2855 * Unmount all filesystems. The list is traversed in reverse order
2856 * of mounting to avoid dependencies.
2857 */
2858void
2859vfs_unmountall(void)
2860{
2861	struct mount *mp;
2862	struct thread *td;
2863	int error;
2864
2865	KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
2866	td = curthread;
2867	/*
2868	 * Since this only runs when rebooting, it is not interlocked.
2869	 */
2870	while(!TAILQ_EMPTY(&mountlist)) {
2871		mp = TAILQ_LAST(&mountlist, mntlist);
2872		error = dounmount(mp, MNT_FORCE, td);
2873		if (error) {
2874			TAILQ_REMOVE(&mountlist, mp, mnt_list);
2875			/*
2876			 * XXX: Due to the way in which we mount the root
2877			 * file system off of devfs, devfs will generate a
2878			 * "busy" warning when we try to unmount it before
2879			 * the root.  Don't print a warning as a result in
2880			 * order to avoid false positive errors that may
2881			 * cause needless upset.
2882			 */
2883			if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
2884				printf("unmount of %s failed (",
2885				    mp->mnt_stat.f_mntonname);
2886				if (error == EBUSY)
2887					printf("BUSY)\n");
2888				else
2889					printf("%d)\n", error);
2890			}
2891		} else {
2892			/* The unmount has removed mp from the mountlist */
2893		}
2894	}
2895}
2896
2897/*
2898 * perform msync on all vnodes under a mount point
2899 * the mount point must be locked.
2900 */
2901void
2902vfs_msync(struct mount *mp, int flags)
2903{
2904	struct vnode *vp, *mvp;
2905	struct vm_object *obj;
2906
2907	MNT_ILOCK(mp);
2908	MNT_VNODE_FOREACH(vp, mp, mvp) {
2909		VI_LOCK(vp);
2910		if ((vp->v_iflag & VI_OBJDIRTY) &&
2911		    (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
2912			MNT_IUNLOCK(mp);
2913			if (!vget(vp,
2914			    LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
2915			    curthread)) {
2916				if (vp->v_vflag & VV_NOSYNC) {	/* unlinked */
2917					vput(vp);
2918					MNT_ILOCK(mp);
2919					continue;
2920				}
2921
2922				obj = vp->v_object;
2923				if (obj != NULL) {
2924					VM_OBJECT_LOCK(obj);
2925					vm_object_page_clean(obj, 0, 0,
2926					    flags == MNT_WAIT ?
2927					    OBJPC_SYNC : OBJPC_NOSYNC);
2928					VM_OBJECT_UNLOCK(obj);
2929				}
2930				vput(vp);
2931			}
2932			MNT_ILOCK(mp);
2933		} else
2934			VI_UNLOCK(vp);
2935	}
2936	MNT_IUNLOCK(mp);
2937}
2938
2939/*
2940 * Mark a vnode as free, putting it up for recycling.
2941 */
2942static void
2943vfree(struct vnode *vp)
2944{
2945
2946	CTR1(KTR_VFS, "vfree vp %p", vp);
2947	ASSERT_VI_LOCKED(vp, "vfree");
2948	mtx_lock(&vnode_free_list_mtx);
2949	VNASSERT(vp->v_op != NULL, vp, ("vfree: vnode already reclaimed."));
2950	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp, ("vnode already free"));
2951	VNASSERT(VSHOULDFREE(vp), vp, ("vfree: freeing when we shouldn't"));
2952	VNASSERT((vp->v_iflag & VI_DOOMED) == 0, vp,
2953	    ("vfree: Freeing doomed vnode"));
2954	if (vp->v_iflag & VI_AGE) {
2955		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2956	} else {
2957		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2958	}
2959	freevnodes++;
2960	vp->v_iflag &= ~VI_AGE;
2961	vp->v_iflag |= VI_FREE;
2962	mtx_unlock(&vnode_free_list_mtx);
2963}
2964
2965/*
2966 * Opposite of vfree() - mark a vnode as in use.
2967 */
2968static void
2969vbusy(struct vnode *vp)
2970{
2971	CTR1(KTR_VFS, "vbusy vp %p", vp);
2972	ASSERT_VI_LOCKED(vp, "vbusy");
2973	VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
2974	VNASSERT(vp->v_op != NULL, vp, ("vbusy: vnode already reclaimed."));
2975
2976	mtx_lock(&vnode_free_list_mtx);
2977	TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2978	freevnodes--;
2979	vp->v_iflag &= ~(VI_FREE|VI_AGE);
2980	mtx_unlock(&vnode_free_list_mtx);
2981}
2982
2983/*
2984 * Initalize per-vnode helper structure to hold poll-related state.
2985 */
2986void
2987v_addpollinfo(struct vnode *vp)
2988{
2989	struct vpollinfo *vi;
2990
2991	vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
2992	if (vp->v_pollinfo != NULL) {
2993		uma_zfree(vnodepoll_zone, vi);
2994		return;
2995	}
2996	vp->v_pollinfo = vi;
2997	mtx_init(&vp->v_pollinfo->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
2998	knlist_init(&vp->v_pollinfo->vpi_selinfo.si_note, vp, vfs_knllock,
2999	    vfs_knlunlock, vfs_knllocked);
3000}
3001
3002/*
3003 * Record a process's interest in events which might happen to
3004 * a vnode.  Because poll uses the historic select-style interface
3005 * internally, this routine serves as both the ``check for any
3006 * pending events'' and the ``record my interest in future events''
3007 * functions.  (These are done together, while the lock is held,
3008 * to avoid race conditions.)
3009 */
3010int
3011vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3012{
3013
3014	if (vp->v_pollinfo == NULL)
3015		v_addpollinfo(vp);
3016	mtx_lock(&vp->v_pollinfo->vpi_lock);
3017	if (vp->v_pollinfo->vpi_revents & events) {
3018		/*
3019		 * This leaves events we are not interested
3020		 * in available for the other process which
3021		 * which presumably had requested them
3022		 * (otherwise they would never have been
3023		 * recorded).
3024		 */
3025		events &= vp->v_pollinfo->vpi_revents;
3026		vp->v_pollinfo->vpi_revents &= ~events;
3027
3028		mtx_unlock(&vp->v_pollinfo->vpi_lock);
3029		return events;
3030	}
3031	vp->v_pollinfo->vpi_events |= events;
3032	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3033	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3034	return 0;
3035}
3036
3037/*
3038 * Routine to create and manage a filesystem syncer vnode.
3039 */
3040#define sync_close ((int (*)(struct  vop_close_args *))nullop)
3041static int	sync_fsync(struct  vop_fsync_args *);
3042static int	sync_inactive(struct  vop_inactive_args *);
3043static int	sync_reclaim(struct  vop_reclaim_args *);
3044
3045static struct vop_vector sync_vnodeops = {
3046	.vop_bypass =	VOP_EOPNOTSUPP,
3047	.vop_close =	sync_close,		/* close */
3048	.vop_fsync =	sync_fsync,		/* fsync */
3049	.vop_inactive =	sync_inactive,	/* inactive */
3050	.vop_reclaim =	sync_reclaim,	/* reclaim */
3051	._vop_lock =	vop_stdlock,	/* lock */
3052	.vop_unlock =	vop_stdunlock,	/* unlock */
3053	.vop_islocked =	vop_stdislocked,	/* islocked */
3054};
3055
3056/*
3057 * Create a new filesystem syncer vnode for the specified mount point.
3058 */
3059int
3060vfs_allocate_syncvnode(struct mount *mp)
3061{
3062	struct vnode *vp;
3063	static long start, incr, next;
3064	int error;
3065
3066	/* Allocate a new vnode */
3067	if ((error = getnewvnode("syncer", mp, &sync_vnodeops, &vp)) != 0) {
3068		mp->mnt_syncer = NULL;
3069		return (error);
3070	}
3071	vp->v_type = VNON;
3072	error = insmntque(vp, mp);
3073	if (error != 0)
3074		panic("vfs_allocate_syncvnode: insmntque failed");
3075	/*
3076	 * Place the vnode onto the syncer worklist. We attempt to
3077	 * scatter them about on the list so that they will go off
3078	 * at evenly distributed times even if all the filesystems
3079	 * are mounted at once.
3080	 */
3081	next += incr;
3082	if (next == 0 || next > syncer_maxdelay) {
3083		start /= 2;
3084		incr /= 2;
3085		if (start == 0) {
3086			start = syncer_maxdelay / 2;
3087			incr = syncer_maxdelay;
3088		}
3089		next = start;
3090	}
3091	VI_LOCK(vp);
3092	vn_syncer_add_to_worklist(&vp->v_bufobj,
3093	    syncdelay > 0 ? next % syncdelay : 0);
3094	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3095	mtx_lock(&sync_mtx);
3096	sync_vnode_count++;
3097	mtx_unlock(&sync_mtx);
3098	VI_UNLOCK(vp);
3099	mp->mnt_syncer = vp;
3100	return (0);
3101}
3102
3103/*
3104 * Do a lazy sync of the filesystem.
3105 */
3106static int
3107sync_fsync(struct vop_fsync_args *ap)
3108{
3109	struct vnode *syncvp = ap->a_vp;
3110	struct mount *mp = syncvp->v_mount;
3111	struct thread *td = ap->a_td;
3112	int error;
3113	struct bufobj *bo;
3114
3115	/*
3116	 * We only need to do something if this is a lazy evaluation.
3117	 */
3118	if (ap->a_waitfor != MNT_LAZY)
3119		return (0);
3120
3121	/*
3122	 * Move ourselves to the back of the sync list.
3123	 */
3124	bo = &syncvp->v_bufobj;
3125	BO_LOCK(bo);
3126	vn_syncer_add_to_worklist(bo, syncdelay);
3127	BO_UNLOCK(bo);
3128
3129	/*
3130	 * Walk the list of vnodes pushing all that are dirty and
3131	 * not already on the sync list.
3132	 */
3133	mtx_lock(&mountlist_mtx);
3134	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_mtx, td) != 0) {
3135		mtx_unlock(&mountlist_mtx);
3136		return (0);
3137	}
3138	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3139		vfs_unbusy(mp, td);
3140		return (0);
3141	}
3142	MNT_ILOCK(mp);
3143	mp->mnt_noasync++;
3144	mp->mnt_kern_flag &= ~MNTK_ASYNC;
3145	MNT_IUNLOCK(mp);
3146	vfs_msync(mp, MNT_NOWAIT);
3147	error = VFS_SYNC(mp, MNT_LAZY, td);
3148	MNT_ILOCK(mp);
3149	mp->mnt_noasync--;
3150	if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
3151		mp->mnt_kern_flag |= MNTK_ASYNC;
3152	MNT_IUNLOCK(mp);
3153	vn_finished_write(mp);
3154	vfs_unbusy(mp, td);
3155	return (error);
3156}
3157
3158/*
3159 * The syncer vnode is no referenced.
3160 */
3161static int
3162sync_inactive(struct vop_inactive_args *ap)
3163{
3164
3165	vgone(ap->a_vp);
3166	return (0);
3167}
3168
3169/*
3170 * The syncer vnode is no longer needed and is being decommissioned.
3171 *
3172 * Modifications to the worklist must be protected by sync_mtx.
3173 */
3174static int
3175sync_reclaim(struct vop_reclaim_args *ap)
3176{
3177	struct vnode *vp = ap->a_vp;
3178	struct bufobj *bo;
3179
3180	VI_LOCK(vp);
3181	bo = &vp->v_bufobj;
3182	vp->v_mount->mnt_syncer = NULL;
3183	if (bo->bo_flag & BO_ONWORKLST) {
3184		mtx_lock(&sync_mtx);
3185		LIST_REMOVE(bo, bo_synclist);
3186		syncer_worklist_len--;
3187		sync_vnode_count--;
3188		mtx_unlock(&sync_mtx);
3189		bo->bo_flag &= ~BO_ONWORKLST;
3190	}
3191	VI_UNLOCK(vp);
3192
3193	return (0);
3194}
3195
3196/*
3197 * Check if vnode represents a disk device
3198 */
3199int
3200vn_isdisk(struct vnode *vp, int *errp)
3201{
3202	int error;
3203
3204	error = 0;
3205	dev_lock();
3206	if (vp->v_type != VCHR)
3207		error = ENOTBLK;
3208	else if (vp->v_rdev == NULL)
3209		error = ENXIO;
3210	else if (vp->v_rdev->si_devsw == NULL)
3211		error = ENXIO;
3212	else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3213		error = ENOTBLK;
3214	dev_unlock();
3215	if (errp != NULL)
3216		*errp = error;
3217	return (error == 0);
3218}
3219
3220/*
3221 * Common filesystem object access control check routine.  Accepts a
3222 * vnode's type, "mode", uid and gid, requested access mode, credentials,
3223 * and optional call-by-reference privused argument allowing vaccess()
3224 * to indicate to the caller whether privilege was used to satisfy the
3225 * request (obsoleted).  Returns 0 on success, or an errno on failure.
3226 *
3227 * The ifdef'd CAPABILITIES version is here for reference, but is not
3228 * actually used.
3229 */
3230int
3231vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3232    mode_t acc_mode, struct ucred *cred, int *privused)
3233{
3234	mode_t dac_granted;
3235	mode_t priv_granted;
3236
3237	/*
3238	 * Look for a normal, non-privileged way to access the file/directory
3239	 * as requested.  If it exists, go with that.
3240	 */
3241
3242	if (privused != NULL)
3243		*privused = 0;
3244
3245	dac_granted = 0;
3246
3247	/* Check the owner. */
3248	if (cred->cr_uid == file_uid) {
3249		dac_granted |= VADMIN;
3250		if (file_mode & S_IXUSR)
3251			dac_granted |= VEXEC;
3252		if (file_mode & S_IRUSR)
3253			dac_granted |= VREAD;
3254		if (file_mode & S_IWUSR)
3255			dac_granted |= (VWRITE | VAPPEND);
3256
3257		if ((acc_mode & dac_granted) == acc_mode)
3258			return (0);
3259
3260		goto privcheck;
3261	}
3262
3263	/* Otherwise, check the groups (first match) */
3264	if (groupmember(file_gid, cred)) {
3265		if (file_mode & S_IXGRP)
3266			dac_granted |= VEXEC;
3267		if (file_mode & S_IRGRP)
3268			dac_granted |= VREAD;
3269		if (file_mode & S_IWGRP)
3270			dac_granted |= (VWRITE | VAPPEND);
3271
3272		if ((acc_mode & dac_granted) == acc_mode)
3273			return (0);
3274
3275		goto privcheck;
3276	}
3277
3278	/* Otherwise, check everyone else. */
3279	if (file_mode & S_IXOTH)
3280		dac_granted |= VEXEC;
3281	if (file_mode & S_IROTH)
3282		dac_granted |= VREAD;
3283	if (file_mode & S_IWOTH)
3284		dac_granted |= (VWRITE | VAPPEND);
3285	if ((acc_mode & dac_granted) == acc_mode)
3286		return (0);
3287
3288privcheck:
3289	/*
3290	 * Build a privilege mask to determine if the set of privileges
3291	 * satisfies the requirements when combined with the granted mask
3292	 * from above.  For each privilege, if the privilege is required,
3293	 * bitwise or the request type onto the priv_granted mask.
3294	 */
3295	priv_granted = 0;
3296
3297	if (type == VDIR) {
3298		/*
3299		 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3300		 * requests, instead of PRIV_VFS_EXEC.
3301		 */
3302		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3303		    !priv_check_cred(cred, PRIV_VFS_LOOKUP, SUSER_ALLOWJAIL))
3304			priv_granted |= VEXEC;
3305	} else {
3306		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3307		    !priv_check_cred(cred, PRIV_VFS_EXEC, SUSER_ALLOWJAIL))
3308			priv_granted |= VEXEC;
3309	}
3310
3311	if ((acc_mode & VREAD) && ((dac_granted & VREAD) == 0) &&
3312	    !priv_check_cred(cred, PRIV_VFS_READ, SUSER_ALLOWJAIL))
3313		priv_granted |= VREAD;
3314
3315	if ((acc_mode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3316	    !priv_check_cred(cred, PRIV_VFS_WRITE, SUSER_ALLOWJAIL))
3317		priv_granted |= (VWRITE | VAPPEND);
3318
3319	if ((acc_mode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3320	    !priv_check_cred(cred, PRIV_VFS_ADMIN, SUSER_ALLOWJAIL))
3321		priv_granted |= VADMIN;
3322
3323	if ((acc_mode & (priv_granted | dac_granted)) == acc_mode) {
3324		/* XXX audit: privilege used */
3325		if (privused != NULL)
3326			*privused = 1;
3327		return (0);
3328	}
3329
3330	return ((acc_mode & VADMIN) ? EPERM : EACCES);
3331}
3332
3333/*
3334 * Credential check based on process requesting service, and per-attribute
3335 * permissions.
3336 */
3337int
3338extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3339    struct thread *td, int access)
3340{
3341
3342	/*
3343	 * Kernel-invoked always succeeds.
3344	 */
3345	if (cred == NOCRED)
3346		return (0);
3347
3348	/*
3349	 * Do not allow privileged processes in jail to directly manipulate
3350	 * system attributes.
3351	 */
3352	switch (attrnamespace) {
3353	case EXTATTR_NAMESPACE_SYSTEM:
3354		/* Potentially should be: return (EPERM); */
3355		return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3356	case EXTATTR_NAMESPACE_USER:
3357		return (VOP_ACCESS(vp, access, cred, td));
3358	default:
3359		return (EPERM);
3360	}
3361}
3362
3363#ifdef DEBUG_VFS_LOCKS
3364/*
3365 * This only exists to supress warnings from unlocked specfs accesses.  It is
3366 * no longer ok to have an unlocked VFS.
3367 */
3368#define	IGNORE_LOCK(vp) ((vp)->v_type == VCHR || (vp)->v_type == VBAD)
3369
3370int vfs_badlock_ddb = 1;	/* Drop into debugger on violation. */
3371SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0, "");
3372
3373int vfs_badlock_mutex = 1;	/* Check for interlock across VOPs. */
3374SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex, 0, "");
3375
3376int vfs_badlock_print = 1;	/* Print lock violations. */
3377SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print, 0, "");
3378
3379#ifdef KDB
3380int vfs_badlock_backtrace = 1;	/* Print backtrace at lock violations. */
3381SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW, &vfs_badlock_backtrace, 0, "");
3382#endif
3383
3384static void
3385vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3386{
3387
3388#ifdef KDB
3389	if (vfs_badlock_backtrace)
3390		kdb_backtrace();
3391#endif
3392	if (vfs_badlock_print)
3393		printf("%s: %p %s\n", str, (void *)vp, msg);
3394	if (vfs_badlock_ddb)
3395		kdb_enter("lock violation");
3396}
3397
3398void
3399assert_vi_locked(struct vnode *vp, const char *str)
3400{
3401
3402	if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3403		vfs_badlock("interlock is not locked but should be", str, vp);
3404}
3405
3406void
3407assert_vi_unlocked(struct vnode *vp, const char *str)
3408{
3409
3410	if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3411		vfs_badlock("interlock is locked but should not be", str, vp);
3412}
3413
3414void
3415assert_vop_locked(struct vnode *vp, const char *str)
3416{
3417
3418	if (vp && !IGNORE_LOCK(vp) && VOP_ISLOCKED(vp, NULL) == 0)
3419		vfs_badlock("is not locked but should be", str, vp);
3420}
3421
3422void
3423assert_vop_unlocked(struct vnode *vp, const char *str)
3424{
3425
3426	if (vp && !IGNORE_LOCK(vp) &&
3427	    VOP_ISLOCKED(vp, curthread) == LK_EXCLUSIVE)
3428		vfs_badlock("is locked but should not be", str, vp);
3429}
3430
3431void
3432assert_vop_elocked(struct vnode *vp, const char *str)
3433{
3434
3435	if (vp && !IGNORE_LOCK(vp) &&
3436	    VOP_ISLOCKED(vp, curthread) != LK_EXCLUSIVE)
3437		vfs_badlock("is not exclusive locked but should be", str, vp);
3438}
3439
3440#if 0
3441void
3442assert_vop_elocked_other(struct vnode *vp, const char *str)
3443{
3444
3445	if (vp && !IGNORE_LOCK(vp) &&
3446	    VOP_ISLOCKED(vp, curthread) != LK_EXCLOTHER)
3447		vfs_badlock("is not exclusive locked by another thread",
3448		    str, vp);
3449}
3450
3451void
3452assert_vop_slocked(struct vnode *vp, const char *str)
3453{
3454
3455	if (vp && !IGNORE_LOCK(vp) &&
3456	    VOP_ISLOCKED(vp, curthread) != LK_SHARED)
3457		vfs_badlock("is not locked shared but should be", str, vp);
3458}
3459#endif /* 0 */
3460#endif /* DEBUG_VFS_LOCKS */
3461
3462void
3463vop_rename_pre(void *ap)
3464{
3465	struct vop_rename_args *a = ap;
3466
3467#ifdef DEBUG_VFS_LOCKS
3468	if (a->a_tvp)
3469		ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
3470	ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
3471	ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
3472	ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
3473
3474	/* Check the source (from). */
3475	if (a->a_tdvp != a->a_fdvp && a->a_tvp != a->a_fdvp)
3476		ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
3477	if (a->a_tvp != a->a_fvp)
3478		ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
3479
3480	/* Check the target. */
3481	if (a->a_tvp)
3482		ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
3483	ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
3484#endif
3485	if (a->a_tdvp != a->a_fdvp)
3486		vhold(a->a_fdvp);
3487	if (a->a_tvp != a->a_fvp)
3488		vhold(a->a_fvp);
3489	vhold(a->a_tdvp);
3490	if (a->a_tvp)
3491		vhold(a->a_tvp);
3492}
3493
3494void
3495vop_strategy_pre(void *ap)
3496{
3497#ifdef DEBUG_VFS_LOCKS
3498	struct vop_strategy_args *a;
3499	struct buf *bp;
3500
3501	a = ap;
3502	bp = a->a_bp;
3503
3504	/*
3505	 * Cluster ops lock their component buffers but not the IO container.
3506	 */
3507	if ((bp->b_flags & B_CLUSTER) != 0)
3508		return;
3509
3510	if (BUF_REFCNT(bp) < 1) {
3511		if (vfs_badlock_print)
3512			printf(
3513			    "VOP_STRATEGY: bp is not locked but should be\n");
3514		if (vfs_badlock_ddb)
3515			kdb_enter("lock violation");
3516	}
3517#endif
3518}
3519
3520void
3521vop_lookup_pre(void *ap)
3522{
3523#ifdef DEBUG_VFS_LOCKS
3524	struct vop_lookup_args *a;
3525	struct vnode *dvp;
3526
3527	a = ap;
3528	dvp = a->a_dvp;
3529	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3530	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3531#endif
3532}
3533
3534void
3535vop_lookup_post(void *ap, int rc)
3536{
3537#ifdef DEBUG_VFS_LOCKS
3538	struct vop_lookup_args *a;
3539	struct vnode *dvp;
3540	struct vnode *vp;
3541
3542	a = ap;
3543	dvp = a->a_dvp;
3544	vp = *(a->a_vpp);
3545
3546	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3547	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3548
3549	if (!rc)
3550		ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
3551#endif
3552}
3553
3554void
3555vop_lock_pre(void *ap)
3556{
3557#ifdef DEBUG_VFS_LOCKS
3558	struct _vop_lock_args *a = ap;
3559
3560	if ((a->a_flags & LK_INTERLOCK) == 0)
3561		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3562	else
3563		ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
3564#endif
3565}
3566
3567void
3568vop_lock_post(void *ap, int rc)
3569{
3570#ifdef DEBUG_VFS_LOCKS
3571	struct _vop_lock_args *a = ap;
3572
3573	ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3574	if (rc == 0)
3575		ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
3576#endif
3577}
3578
3579void
3580vop_unlock_pre(void *ap)
3581{
3582#ifdef DEBUG_VFS_LOCKS
3583	struct vop_unlock_args *a = ap;
3584
3585	if (a->a_flags & LK_INTERLOCK)
3586		ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
3587	ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
3588#endif
3589}
3590
3591void
3592vop_unlock_post(void *ap, int rc)
3593{
3594#ifdef DEBUG_VFS_LOCKS
3595	struct vop_unlock_args *a = ap;
3596
3597	if (a->a_flags & LK_INTERLOCK)
3598		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
3599#endif
3600}
3601
3602void
3603vop_create_post(void *ap, int rc)
3604{
3605	struct vop_create_args *a = ap;
3606
3607	if (!rc)
3608		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3609}
3610
3611void
3612vop_link_post(void *ap, int rc)
3613{
3614	struct vop_link_args *a = ap;
3615
3616	if (!rc) {
3617		VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
3618		VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
3619	}
3620}
3621
3622void
3623vop_mkdir_post(void *ap, int rc)
3624{
3625	struct vop_mkdir_args *a = ap;
3626
3627	if (!rc)
3628		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3629}
3630
3631void
3632vop_mknod_post(void *ap, int rc)
3633{
3634	struct vop_mknod_args *a = ap;
3635
3636	if (!rc)
3637		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3638}
3639
3640void
3641vop_remove_post(void *ap, int rc)
3642{
3643	struct vop_remove_args *a = ap;
3644
3645	if (!rc) {
3646		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3647		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3648	}
3649}
3650
3651void
3652vop_rename_post(void *ap, int rc)
3653{
3654	struct vop_rename_args *a = ap;
3655
3656	if (!rc) {
3657		VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
3658		VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
3659		VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
3660		if (a->a_tvp)
3661			VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
3662	}
3663	if (a->a_tdvp != a->a_fdvp)
3664		vdrop(a->a_fdvp);
3665	if (a->a_tvp != a->a_fvp)
3666		vdrop(a->a_fvp);
3667	vdrop(a->a_tdvp);
3668	if (a->a_tvp)
3669		vdrop(a->a_tvp);
3670}
3671
3672void
3673vop_rmdir_post(void *ap, int rc)
3674{
3675	struct vop_rmdir_args *a = ap;
3676
3677	if (!rc) {
3678		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3679		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3680	}
3681}
3682
3683void
3684vop_setattr_post(void *ap, int rc)
3685{
3686	struct vop_setattr_args *a = ap;
3687
3688	if (!rc)
3689		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
3690}
3691
3692void
3693vop_symlink_post(void *ap, int rc)
3694{
3695	struct vop_symlink_args *a = ap;
3696
3697	if (!rc)
3698		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3699}
3700
3701static struct knlist fs_knlist;
3702
3703static void
3704vfs_event_init(void *arg)
3705{
3706	knlist_init(&fs_knlist, NULL, NULL, NULL, NULL);
3707}
3708/* XXX - correct order? */
3709SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
3710
3711void
3712vfs_event_signal(fsid_t *fsid, u_int32_t event, intptr_t data __unused)
3713{
3714
3715	KNOTE_UNLOCKED(&fs_knlist, event);
3716}
3717
3718static int	filt_fsattach(struct knote *kn);
3719static void	filt_fsdetach(struct knote *kn);
3720static int	filt_fsevent(struct knote *kn, long hint);
3721
3722struct filterops fs_filtops =
3723	{ 0, filt_fsattach, filt_fsdetach, filt_fsevent };
3724
3725static int
3726filt_fsattach(struct knote *kn)
3727{
3728
3729	kn->kn_flags |= EV_CLEAR;
3730	knlist_add(&fs_knlist, kn, 0);
3731	return (0);
3732}
3733
3734static void
3735filt_fsdetach(struct knote *kn)
3736{
3737
3738	knlist_remove(&fs_knlist, kn, 0);
3739}
3740
3741static int
3742filt_fsevent(struct knote *kn, long hint)
3743{
3744
3745	kn->kn_fflags |= hint;
3746	return (kn->kn_fflags != 0);
3747}
3748
3749static int
3750sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
3751{
3752	struct vfsidctl vc;
3753	int error;
3754	struct mount *mp;
3755
3756	error = SYSCTL_IN(req, &vc, sizeof(vc));
3757	if (error)
3758		return (error);
3759	if (vc.vc_vers != VFS_CTL_VERS1)
3760		return (EINVAL);
3761	mp = vfs_getvfs(&vc.vc_fsid);
3762	if (mp == NULL)
3763		return (ENOENT);
3764	/* ensure that a specific sysctl goes to the right filesystem. */
3765	if (strcmp(vc.vc_fstypename, "*") != 0 &&
3766	    strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
3767		vfs_rel(mp);
3768		return (EINVAL);
3769	}
3770	VCTLTOREQ(&vc, req);
3771	error = VFS_SYSCTL(mp, vc.vc_op, req);
3772	vfs_rel(mp);
3773	return (error);
3774}
3775
3776SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLFLAG_WR, NULL, 0, sysctl_vfs_ctl, "",
3777    "Sysctl by fsid");
3778
3779/*
3780 * Function to initialize a va_filerev field sensibly.
3781 * XXX: Wouldn't a random number make a lot more sense ??
3782 */
3783u_quad_t
3784init_va_filerev(void)
3785{
3786	struct bintime bt;
3787
3788	getbinuptime(&bt);
3789	return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
3790}
3791
3792static int	filt_vfsread(struct knote *kn, long hint);
3793static int	filt_vfswrite(struct knote *kn, long hint);
3794static int	filt_vfsvnode(struct knote *kn, long hint);
3795static void	filt_vfsdetach(struct knote *kn);
3796static struct filterops vfsread_filtops =
3797	{ 1, NULL, filt_vfsdetach, filt_vfsread };
3798static struct filterops vfswrite_filtops =
3799	{ 1, NULL, filt_vfsdetach, filt_vfswrite };
3800static struct filterops vfsvnode_filtops =
3801	{ 1, NULL, filt_vfsdetach, filt_vfsvnode };
3802
3803static void
3804vfs_knllock(void *arg)
3805{
3806	struct vnode *vp = arg;
3807
3808	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, curthread);
3809}
3810
3811static void
3812vfs_knlunlock(void *arg)
3813{
3814	struct vnode *vp = arg;
3815
3816	VOP_UNLOCK(vp, 0, curthread);
3817}
3818
3819static int
3820vfs_knllocked(void *arg)
3821{
3822	struct vnode *vp = arg;
3823
3824	return (VOP_ISLOCKED(vp, curthread) == LK_EXCLUSIVE);
3825}
3826
3827int
3828vfs_kqfilter(struct vop_kqfilter_args *ap)
3829{
3830	struct vnode *vp = ap->a_vp;
3831	struct knote *kn = ap->a_kn;
3832	struct knlist *knl;
3833
3834	switch (kn->kn_filter) {
3835	case EVFILT_READ:
3836		kn->kn_fop = &vfsread_filtops;
3837		break;
3838	case EVFILT_WRITE:
3839		kn->kn_fop = &vfswrite_filtops;
3840		break;
3841	case EVFILT_VNODE:
3842		kn->kn_fop = &vfsvnode_filtops;
3843		break;
3844	default:
3845		return (EINVAL);
3846	}
3847
3848	kn->kn_hook = (caddr_t)vp;
3849
3850	if (vp->v_pollinfo == NULL)
3851		v_addpollinfo(vp);
3852	if (vp->v_pollinfo == NULL)
3853		return (ENOMEM);
3854	knl = &vp->v_pollinfo->vpi_selinfo.si_note;
3855	knlist_add(knl, kn, 0);
3856
3857	return (0);
3858}
3859
3860/*
3861 * Detach knote from vnode
3862 */
3863static void
3864filt_vfsdetach(struct knote *kn)
3865{
3866	struct vnode *vp = (struct vnode *)kn->kn_hook;
3867
3868	KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
3869	knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
3870}
3871
3872/*ARGSUSED*/
3873static int
3874filt_vfsread(struct knote *kn, long hint)
3875{
3876	struct vnode *vp = (struct vnode *)kn->kn_hook;
3877	struct vattr va;
3878
3879	/*
3880	 * filesystem is gone, so set the EOF flag and schedule
3881	 * the knote for deletion.
3882	 */
3883	if (hint == NOTE_REVOKE) {
3884		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
3885		return (1);
3886	}
3887
3888	if (VOP_GETATTR(vp, &va, curthread->td_ucred, curthread))
3889		return (0);
3890
3891	kn->kn_data = va.va_size - kn->kn_fp->f_offset;
3892	return (kn->kn_data != 0);
3893}
3894
3895/*ARGSUSED*/
3896static int
3897filt_vfswrite(struct knote *kn, long hint)
3898{
3899	/*
3900	 * filesystem is gone, so set the EOF flag and schedule
3901	 * the knote for deletion.
3902	 */
3903	if (hint == NOTE_REVOKE)
3904		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
3905
3906	kn->kn_data = 0;
3907	return (1);
3908}
3909
3910static int
3911filt_vfsvnode(struct knote *kn, long hint)
3912{
3913	if (kn->kn_sfflags & hint)
3914		kn->kn_fflags |= hint;
3915	if (hint == NOTE_REVOKE) {
3916		kn->kn_flags |= EV_EOF;
3917		return (1);
3918	}
3919	return (kn->kn_fflags != 0);
3920}
3921
3922int
3923vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
3924{
3925	int error;
3926
3927	if (dp->d_reclen > ap->a_uio->uio_resid)
3928		return (ENAMETOOLONG);
3929	error = uiomove(dp, dp->d_reclen, ap->a_uio);
3930	if (error) {
3931		if (ap->a_ncookies != NULL) {
3932			if (ap->a_cookies != NULL)
3933				free(ap->a_cookies, M_TEMP);
3934			ap->a_cookies = NULL;
3935			*ap->a_ncookies = 0;
3936		}
3937		return (error);
3938	}
3939	if (ap->a_ncookies == NULL)
3940		return (0);
3941
3942	KASSERT(ap->a_cookies,
3943	    ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
3944
3945	*ap->a_cookies = realloc(*ap->a_cookies,
3946	    (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
3947	(*ap->a_cookies)[*ap->a_ncookies] = off;
3948	return (0);
3949}
3950
3951/*
3952 * Mark for update the access time of the file if the filesystem
3953 * supports VA_MARK_ATIME.  This functionality is used by execve
3954 * and mmap, so we want to avoid the synchronous I/O implied by
3955 * directly setting va_atime for the sake of efficiency.
3956 */
3957void
3958vfs_mark_atime(struct vnode *vp, struct thread *td)
3959{
3960	struct vattr atimeattr;
3961
3962	if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
3963		VATTR_NULL(&atimeattr);
3964		atimeattr.va_vaflags |= VA_MARK_ATIME;
3965		(void)VOP_SETATTR(vp, &atimeattr, td->td_ucred, td);
3966	}
3967}
3968