vfs_subr.c revision 99220
1159967Sobrien/*
2159952Sobrien * Copyright (c) 1989, 1993
3159952Sobrien *	The Regents of the University of California.  All rights reserved.
4159952Sobrien * (c) UNIX System Laboratories, Inc.
5159952Sobrien * All or some portions of this file are derived from material licensed
6159952Sobrien * to the University of California by American Telephone and Telegraph
7159952Sobrien * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8159952Sobrien * the permission of UNIX System Laboratories, Inc.
9159952Sobrien *
10159952Sobrien * Redistribution and use in source and binary forms, with or without
11159952Sobrien * modification, are permitted provided that the following conditions
12159952Sobrien * are met:
13159952Sobrien * 1. Redistributions of source code must retain the above copyright
14159952Sobrien *    notice, this list of conditions and the following disclaimer.
15159952Sobrien * 2. Redistributions in binary form must reproduce the above copyright
16159952Sobrien *    notice, this list of conditions and the following disclaimer in the
17159967Sobrien *    documentation and/or other materials provided with the distribution.
18159967Sobrien * 3. All advertising materials mentioning features or use of this software
19159952Sobrien *    must display the following acknowledgement:
20159952Sobrien *	This product includes software developed by the University of
21170589Syongari *	California, Berkeley and its contributors.
22170589Syongari * 4. Neither the name of the University nor the names of its contributors
23163504Sobrien *    may be used to endorse or promote products derived from this software
24159952Sobrien *    without specific prior written permission.
25170589Syongari *
26170589Syongari * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27170589Syongari * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28170589Syongari * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29170589Syongari * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30170589Syongari * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31164650Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32164650Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33164650Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34164650Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35164650Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36164650Sobrien * SUCH DAMAGE.
37159952Sobrien *
38170589Syongari *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
39170589Syongari * $FreeBSD: head/sys/kern/vfs_subr.c 99220 2002-07-01 17:59:40Z iedowse $
40170589Syongari */
41170589Syongari
42159952Sobrien/*
43170589Syongari * External virtual filesystem routines
44170595Syongari */
45170604Syongari#include "opt_ddb.h"
46170589Syongari
47163504Sobrien#include <sys/param.h>
48163504Sobrien#include <sys/systm.h>
49163504Sobrien#include <sys/bio.h>
50163504Sobrien#include <sys/buf.h>
51170589Syongari#include <sys/conf.h>
52170589Syongari#include <sys/eventhandler.h>
53170589Syongari#include <sys/fcntl.h>
54170589Syongari#include <sys/kernel.h>
55163504Sobrien#include <sys/kthread.h>
56163504Sobrien#include <sys/malloc.h>
57163504Sobrien#include <sys/mount.h>
58163504Sobrien#include <sys/namei.h>
59163504Sobrien#include <sys/stat.h>
60163504Sobrien#include <sys/sysctl.h>
61163504Sobrien#include <sys/syslog.h>
62163504Sobrien#include <sys/vmmeter.h>
63163504Sobrien#include <sys/vnode.h>
64163504Sobrien
65163504Sobrien#include <vm/vm.h>
66163504Sobrien#include <vm/vm_object.h>
67163504Sobrien#include <vm/vm_extern.h>
68163504Sobrien#include <vm/pmap.h>
69163504Sobrien#include <vm/vm_map.h>
70163504Sobrien#include <vm/vm_page.h>
71163504Sobrien#include <vm/uma.h>
72163504Sobrien
73163504Sobrienstatic MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
74163504Sobrien
75163504Sobrienstatic void	addalias(struct vnode *vp, dev_t nvp_rdev);
76163504Sobrienstatic void	insmntque(struct vnode *vp, struct mount *mp);
77163504Sobrienstatic void	vclean(struct vnode *vp, int flags, struct thread *td);
78163504Sobrienstatic void	vlruvp(struct vnode *vp);
79163504Sobrien
80163504Sobrien/*
81163504Sobrien * Number of vnodes in existence.  Increased whenever getnewvnode()
82163504Sobrien * allocates a new vnode, never decreased.
83170589Syongari */
84163504Sobrienstatic unsigned long	numvnodes;
85163504Sobrien
86163504SobrienSYSCTL_LONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
87163504Sobrien
88163504Sobrien/*
89163504Sobrien * Conversion tables for conversion from vnode types to inode formats
90183561Syongari * and back.
91183561Syongari */
92183561Syongarienum vtype iftovt_tab[16] = {
93163504Sobrien	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
94163504Sobrien	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
95163504Sobrien};
96163504Sobrienint vttoif_tab[9] = {
97163504Sobrien	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
98183561Syongari	S_IFSOCK, S_IFIFO, S_IFMT,
99183561Syongari};
100183561Syongari
101183561Syongari/*
102183561Syongari * List of vnodes that are ready for recycling.
103183561Syongari */
104183561Syongaristatic TAILQ_HEAD(freelst, vnode) vnode_free_list;
105183561Syongari
106183561Syongari/*
107183561Syongari * Minimum number of free vnodes.  If there are fewer than this free vnodes,
108183561Syongari * getnewvnode() will return a newly allocated vnode.
109183561Syongari */
110183561Syongaristatic u_long wantfreevnodes = 25;
111183561SyongariSYSCTL_LONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
112183561Syongari/* Number of vnodes in the free list. */
113183561Syongaristatic u_long freevnodes;
114183561SyongariSYSCTL_LONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
115183561Syongari
116183561Syongari/*
117183561Syongari * Various variables used for debugging the new implementation of
118183561Syongari * reassignbuf().
119183561Syongari * XXX these are probably of (very) limited utility now.
120183561Syongari */
121183561Syongaristatic int reassignbufcalls;
122183561SyongariSYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
123183561Syongaristatic int reassignbufloops;
124183561SyongariSYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW, &reassignbufloops, 0, "");
125163504Sobrienstatic int reassignbufsortgood;
126170589SyongariSYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW, &reassignbufsortgood, 0, "");
127170589Syongaristatic int reassignbufsortbad;
128170589SyongariSYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW, &reassignbufsortbad, 0, "");
129170589Syongari/* Set to 0 for old insertion-sort based reassignbuf, 1 for modern method. */
130159952Sobrienstatic int reassignbufmethod = 1;
131170589SyongariSYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW, &reassignbufmethod, 0, "");
132170589Syongaristatic int nameileafonly;
133170589SyongariSYSCTL_INT(_vfs, OID_AUTO, nameileafonly, CTLFLAG_RW, &nameileafonly, 0, "");
134170589Syongari
135163504Sobrien#ifdef ENABLE_VFS_IOOPT
136163504Sobrien/* See NOTES for a description of this setting. */
137163504Sobrienint vfs_ioopt;
138163504SobrienSYSCTL_INT(_vfs, OID_AUTO, ioopt, CTLFLAG_RW, &vfs_ioopt, 0, "");
139159952Sobrien#endif
140163504Sobrien
141159952Sobrien/* List of mounted filesystems. */
142170589Syongaristruct mntlist mountlist = TAILQ_HEAD_INITIALIZER(mountlist);
143170589Syongari
144170589Syongari/* For any iteration/modification of mountlist */
145163504Sobrienstruct mtx mountlist_mtx;
146163504Sobrien
147163504Sobrien/* For any iteration/modification of mnt_vnodelist */
148163504Sobrienstruct mtx mntvnode_mtx;
149163504Sobrien
150163504Sobrien/*
151159952Sobrien * Cache for the mount type id assigned to NFS.  This is used for
152163504Sobrien * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
153163504Sobrien */
154163504Sobrienint	nfs_mount_type = -1;
155163504Sobrien
156163504Sobrien/* To keep more than one thread at a time from running vfs_getnewfsid */
157163504Sobrienstatic struct mtx mntid_mtx;
158163504Sobrien
159163504Sobrien/* For any iteration/modification of vnode_free_list */
160163504Sobrienstatic struct mtx vnode_free_list_mtx;
161159952Sobrien
162163504Sobrien/*
163159952Sobrien * For any iteration/modification of dev->si_hlist (linked through
164159952Sobrien * v_specnext)
165159952Sobrien */
166159952Sobrienstatic struct mtx spechash_mtx;
167163504Sobrien
168163504Sobrien/* Publicly exported FS */
169163504Sobrienstruct nfs_public nfs_pub;
170163504Sobrien
171163504Sobrien/* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
172163504Sobrienstatic uma_zone_t vnode_zone;
173163504Sobrienstatic uma_zone_t vnodepoll_zone;
174163504Sobrien
175163504Sobrien/* Set to 1 to print out reclaim of active vnodes */
176170589Syongariint	prtactive;
177170589Syongari
178170589Syongari/*
179170589Syongari * The workitem queue.
180170589Syongari *
181164656Sobrien * It is useful to delay writes of file data and filesystem metadata
182159952Sobrien * for tens of seconds so that quickly created and deleted files need
183159952Sobrien * not waste disk bandwidth being created and removed. To realize this,
184163504Sobrien * we append vnodes to a "workitem" queue. When running with a soft
185159952Sobrien * updates implementation, most pending metadata dependencies should
186163504Sobrien * not wait for more than a few seconds. Thus, mounted on block devices
187159952Sobrien * are delayed only about a half the time that file data is delayed.
188163504Sobrien * Similarly, directory updates are more critical, so are only delayed
189163504Sobrien * about a third the time that file data is delayed. Thus, there are
190159952Sobrien * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
191170589Syongari * one each second (driven off the filesystem syncer process). The
192170589Syongari * syncer_delayno variable indicates the next queue that is to be processed.
193215132Syongari * Items that need to be processed soon are placed in this queue:
194170589Syongari *
195163504Sobrien *	syncer_workitem_pending[syncer_delayno]
196159952Sobrien *
197163504Sobrien * A delay of fifteen seconds is done by placing the request fifteen
198163504Sobrien * entries later in the queue:
199159952Sobrien *
200163504Sobrien *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
201163504Sobrien *
202163504Sobrien */
203159952Sobrienstatic int syncer_delayno;
204163504Sobrienstatic long syncer_mask;
205170589SyongariLIST_HEAD(synclist, vnode);
206163504Sobrienstatic struct synclist *syncer_workitem_pending;
207159952Sobrien
208170589Syongari#define SYNCER_MAXDELAY		32
209170589Syongaristatic int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
210170589Syongaristatic int syncdelay = 30;		/* max time to delay syncing data */
211163504Sobrienstatic int filedelay = 30;		/* time to delay syncing files */
212163504SobrienSYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
213163504Sobrienstatic int dirdelay = 29;		/* time to delay syncing directories */
214163504SobrienSYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
215159952Sobrienstatic int metadelay = 28;		/* time to delay syncing metadata */
216183561SyongariSYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
217183561Syongaristatic int rushjob;		/* number of slots to run ASAP */
218183561Syongaristatic int stat_rush_requests;	/* number of times I/O speeded up */
219183561SyongariSYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
220170589Syongari
221170589Syongari/*
222170589Syongari * Number of vnodes we want to exist at any one time.  This is mostly used
223170589Syongari * to size hash tables in vnode-related code.  It is normally not used in
224170589Syongari * getnewvnode(), as wantfreevnodes is normally nonzero.)
225170589Syongari *
226170589Syongari * XXX desiredvnodes is historical cruft and should not exist.
227170589Syongari */
228170589Syongariint desiredvnodes;
229170589SyongariSYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
230170589Syongari    &desiredvnodes, 0, "Maximum number of vnodes");
231170589Syongaristatic int minvnodes;
232170589SyongariSYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
233170589Syongari    &minvnodes, 0, "Minimum number of vnodes");
234170589Syongaristatic int vnlru_nowhere;
235159952SobrienSYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW, &vnlru_nowhere, 0,
236159952Sobrien    "Number of times the vnlru process ran without success");
237159952Sobrien
238159952Sobrien/* Hook for calling soft updates */
239159952Sobrienint (*softdep_process_worklist_hook)(struct mount *);
240163504Sobrien
241163504Sobrien#ifdef DEBUG_VFS_LOCKS
242163504Sobrien/* Print lock violations */
243163504Sobrienint vfs_badlock_print = 1;
244163504Sobrien/* Panic on violation */
245163504Sobrienint vfs_badlock_panic = 1;
246163504Sobrien#endif
247163504Sobrien
248159952Sobrienvoid
249159952Sobrienv_addpollinfo(struct vnode *vp)
250163504Sobrien{
251159952Sobrien	vp->v_pollinfo = uma_zalloc(vnodepoll_zone, M_WAITOK);
252159952Sobrien	mtx_init(&vp->v_pollinfo->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
253159952Sobrien}
254159952Sobrien
255159952Sobrien/*
256159952Sobrien * Initialize the vnode management data structures.
257159952Sobrien */
258163504Sobrienstatic void
259163504Sobrienvntblinit(void *dummy __unused)
260159952Sobrien{
261159952Sobrien
262163504Sobrien	desiredvnodes = maxproc + cnt.v_page_count / 4;
263163504Sobrien	minvnodes = desiredvnodes / 4;
264163504Sobrien	mtx_init(&mountlist_mtx, "mountlist", NULL, MTX_DEF);
265163504Sobrien	mtx_init(&mntvnode_mtx, "mntvnode", NULL, MTX_DEF);
266163504Sobrien	mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
267163504Sobrien	mtx_init(&spechash_mtx, "spechash", NULL, MTX_DEF);
268163504Sobrien	TAILQ_INIT(&vnode_free_list);
269163504Sobrien	mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
270159952Sobrien	vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
271159952Sobrien	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
272163504Sobrien	vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
273159952Sobrien	      NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
274159952Sobrien	/*
275170589Syongari	 * Initialize the filesystem syncer.
276170589Syongari	 */
277159952Sobrien	syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
278170589Syongari		&syncer_mask);
279170589Syongari	syncer_maxdelay = syncer_mask + 1;
280170589Syongari}
281163504SobrienSYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL)
282163504Sobrien
283170589Syongari
284170589Syongari/*
285163504Sobrien * Mark a mount point as busy. Used to synchronize access and to delay
286170589Syongari * unmounting. Interlock is not released on failure.
287170589Syongari */
288163504Sobrienint
289159952Sobrienvfs_busy(mp, flags, interlkp, td)
290163504Sobrien	struct mount *mp;
291170589Syongari	int flags;
292159952Sobrien	struct mtx *interlkp;
293163504Sobrien	struct thread *td;
294170589Syongari{
295159967Sobrien	int lkflags;
296170589Syongari
297170589Syongari	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
298159967Sobrien		if (flags & LK_NOWAIT)
299159967Sobrien			return (ENOENT);
300159967Sobrien		mp->mnt_kern_flag |= MNTK_MWAIT;
301159967Sobrien		/*
302159967Sobrien		 * Since all busy locks are shared except the exclusive
303159967Sobrien		 * lock granted when unmounting, the only place that a
304159967Sobrien		 * wakeup needs to be done is at the release of the
305159967Sobrien		 * exclusive lock at the end of dounmount.
306159967Sobrien		 */
307159967Sobrien		msleep(mp, interlkp, PVFS, "vfs_busy", 0);
308159967Sobrien		return (ENOENT);
309159967Sobrien	}
310159967Sobrien	lkflags = LK_SHARED | LK_NOPAUSE;
311159967Sobrien	if (interlkp)
312159967Sobrien		lkflags |= LK_INTERLOCK;
313159967Sobrien	if (lockmgr(&mp->mnt_lock, lkflags, interlkp, td))
314159967Sobrien		panic("vfs_busy: unexpected lock failure");
315159967Sobrien	return (0);
316159967Sobrien}
317162212Sobrien
318162212Sobrien/*
319162212Sobrien * Free a busy filesystem.
320162212Sobrien */
321162212Sobrienvoid
322162212Sobrienvfs_unbusy(mp, td)
323162212Sobrien	struct mount *mp;
324162212Sobrien	struct thread *td;
325170589Syongari{
326170589Syongari
327170589Syongari	lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, td);
328170589Syongari}
329178055Syongari
330178055Syongari/*
331178055Syongari * Lookup a filesystem type, and if found allocate and initialize
332178055Syongari * a mount structure for it.
333183509Syongari *
334183509Syongari * Devname is usually updated by mount(8) after booting.
335183509Syongari */
336183509Syongariint
337183509Syongarivfs_rootmountalloc(fstypename, devname, mpp)
338183509Syongari	char *fstypename;
339183509Syongari	char *devname;
340183509Syongari	struct mount **mpp;
341159967Sobrien{
342159967Sobrien	struct thread *td = curthread;	/* XXX */
343159967Sobrien	struct vfsconf *vfsp;
344159967Sobrien	struct mount *mp;
345159967Sobrien
346159967Sobrien	if (fstypename == NULL)
347159967Sobrien		return (ENODEV);
348159967Sobrien	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
349159967Sobrien		if (!strcmp(vfsp->vfc_name, fstypename))
350163504Sobrien			break;
351163504Sobrien	if (vfsp == NULL)
352163504Sobrien		return (ENODEV);
353163504Sobrien	mp = malloc((u_long)sizeof(struct mount), M_MOUNT, M_WAITOK | M_ZERO);
354163504Sobrien	lockinit(&mp->mnt_lock, PVFS, "vfslock", 0, LK_NOPAUSE);
355163504Sobrien	(void)vfs_busy(mp, LK_NOWAIT, 0, td);
356163504Sobrien	TAILQ_INIT(&mp->mnt_nvnodelist);
357163504Sobrien	TAILQ_INIT(&mp->mnt_reservedvnlist);
358163504Sobrien	mp->mnt_vfc = vfsp;
359163504Sobrien	mp->mnt_op = vfsp->vfc_vfsops;
360163504Sobrien	mp->mnt_flag = MNT_RDONLY;
361	mp->mnt_vnodecovered = NULLVP;
362	vfsp->vfc_refcount++;
363	mp->mnt_iosize_max = DFLTPHYS;
364	mp->mnt_stat.f_type = vfsp->vfc_typenum;
365	mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
366	strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
367	mp->mnt_stat.f_mntonname[0] = '/';
368	mp->mnt_stat.f_mntonname[1] = 0;
369	(void) copystr(devname, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, 0);
370	*mpp = mp;
371	return (0);
372}
373
374/*
375 * Find an appropriate filesystem to use for the root. If a filesystem
376 * has not been preselected, walk through the list of known filesystems
377 * trying those that have mountroot routines, and try them until one
378 * works or we have tried them all.
379 */
380#ifdef notdef	/* XXX JH */
381int
382lite2_vfs_mountroot()
383{
384	struct vfsconf *vfsp;
385	extern int (*lite2_mountroot)(void);
386	int error;
387
388	if (lite2_mountroot != NULL)
389		return ((*lite2_mountroot)());
390	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
391		if (vfsp->vfc_mountroot == NULL)
392			continue;
393		if ((error = (*vfsp->vfc_mountroot)()) == 0)
394			return (0);
395		printf("%s_mountroot failed: %d\n", vfsp->vfc_name, error);
396	}
397	return (ENODEV);
398}
399#endif
400
401/*
402 * Lookup a mount point by filesystem identifier.
403 */
404struct mount *
405vfs_getvfs(fsid)
406	fsid_t *fsid;
407{
408	register struct mount *mp;
409
410	mtx_lock(&mountlist_mtx);
411	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
412		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
413		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
414			mtx_unlock(&mountlist_mtx);
415			return (mp);
416	    }
417	}
418	mtx_unlock(&mountlist_mtx);
419	return ((struct mount *) 0);
420}
421
422/*
423 * Get a new unique fsid.  Try to make its val[0] unique, since this value
424 * will be used to create fake device numbers for stat().  Also try (but
425 * not so hard) make its val[0] unique mod 2^16, since some emulators only
426 * support 16-bit device numbers.  We end up with unique val[0]'s for the
427 * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
428 *
429 * Keep in mind that several mounts may be running in parallel.  Starting
430 * the search one past where the previous search terminated is both a
431 * micro-optimization and a defense against returning the same fsid to
432 * different mounts.
433 */
434void
435vfs_getnewfsid(mp)
436	struct mount *mp;
437{
438	static u_int16_t mntid_base;
439	fsid_t tfsid;
440	int mtype;
441
442	mtx_lock(&mntid_mtx);
443	mtype = mp->mnt_vfc->vfc_typenum;
444	tfsid.val[1] = mtype;
445	mtype = (mtype & 0xFF) << 24;
446	for (;;) {
447		tfsid.val[0] = makeudev(255,
448		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
449		mntid_base++;
450		if (vfs_getvfs(&tfsid) == NULL)
451			break;
452	}
453	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
454	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
455	mtx_unlock(&mntid_mtx);
456}
457
458/*
459 * Knob to control the precision of file timestamps:
460 *
461 *   0 = seconds only; nanoseconds zeroed.
462 *   1 = seconds and nanoseconds, accurate within 1/HZ.
463 *   2 = seconds and nanoseconds, truncated to microseconds.
464 * >=3 = seconds and nanoseconds, maximum precision.
465 */
466enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
467
468static int timestamp_precision = TSP_SEC;
469SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
470    &timestamp_precision, 0, "");
471
472/*
473 * Get a current timestamp.
474 */
475void
476vfs_timestamp(tsp)
477	struct timespec *tsp;
478{
479	struct timeval tv;
480
481	switch (timestamp_precision) {
482	case TSP_SEC:
483		tsp->tv_sec = time_second;
484		tsp->tv_nsec = 0;
485		break;
486	case TSP_HZ:
487		getnanotime(tsp);
488		break;
489	case TSP_USEC:
490		microtime(&tv);
491		TIMEVAL_TO_TIMESPEC(&tv, tsp);
492		break;
493	case TSP_NSEC:
494	default:
495		nanotime(tsp);
496		break;
497	}
498}
499
500/*
501 * Build a linked list of mount options from a struct uio.
502 */
503int
504vfs_buildopts(struct uio *auio, struct vfsoptlist **options)
505{
506	struct vfsoptlist *opts;
507	struct vfsopt *opt;
508	unsigned int i, iovcnt;
509	int error, namelen, optlen;
510
511	iovcnt = auio->uio_iovcnt;
512	opts = malloc(sizeof(struct vfsoptlist), M_MOUNT, M_WAITOK);
513	TAILQ_INIT(opts);
514	for (i = 0; i < iovcnt; i += 2) {
515		opt = malloc(sizeof(struct vfsopt), M_MOUNT, M_WAITOK);
516		namelen = auio->uio_iov[i].iov_len;
517		optlen = auio->uio_iov[i + 1].iov_len;
518		opt->name = malloc(namelen, M_MOUNT, M_WAITOK);
519		opt->value = malloc(optlen, M_MOUNT, M_WAITOK);
520		opt->len = optlen;
521		if (auio->uio_segflg == UIO_SYSSPACE) {
522			bcopy(auio->uio_iov[i].iov_base, opt->name, namelen);
523			bcopy(auio->uio_iov[i + 1].iov_base, opt->value,
524			    optlen);
525		} else {
526			error = copyin(auio->uio_iov[i].iov_base, opt->name,
527			    namelen);
528			if (!error)
529				error = copyin(auio->uio_iov[i + 1].iov_base,
530				    opt->value, optlen);
531			if (error)
532				goto bad;
533		}
534		TAILQ_INSERT_TAIL(opts, opt, link);
535	}
536	*options = opts;
537	return (0);
538bad:
539	vfs_freeopts(opts);
540	return (error);
541}
542
543/*
544 * Get a mount option by its name.
545 *
546 * Return 0 if the option was found, ENOENT otherwise.
547 * If len is non-NULL it will be filled with the length
548 * of the option. If buf is non-NULL, it will be filled
549 * with the address of the option.
550 */
551int
552vfs_getopt(opts, name, buf, len)
553	struct vfsoptlist *opts;
554	const char *name;
555	void **buf;
556	int *len;
557{
558	struct vfsopt *opt;
559
560	TAILQ_FOREACH(opt, opts, link) {
561		if (strcmp(name, opt->name) == 0) {
562			if (len != NULL)
563				*len = opt->len;
564			if (buf != NULL)
565				*buf = opt->value;
566			return (0);
567		}
568	}
569	return (ENOENT);
570}
571
572/*
573 * Find and copy a mount option.
574 *
575 * The size of the buffer has to be specified
576 * in len, if it is not the same length as the
577 * mount option, EINVAL is returned.
578 * Returns ENOENT if the option is not found.
579 */
580int
581vfs_copyopt(opts, name, dest, len)
582	struct vfsoptlist *opts;
583	const char *name;
584	void *dest;
585	int len;
586{
587	struct vfsopt *opt;
588
589	TAILQ_FOREACH(opt, opts, link) {
590		if (strcmp(name, opt->name) == 0) {
591			if (len != opt->len)
592				return (EINVAL);
593			bcopy(opt->value, dest, opt->len);
594			return (0);
595		}
596	}
597	return (ENOENT);
598}
599
600/*
601 * Set vnode attributes to VNOVAL
602 */
603void
604vattr_null(vap)
605	register struct vattr *vap;
606{
607
608	vap->va_type = VNON;
609	vap->va_size = VNOVAL;
610	vap->va_bytes = VNOVAL;
611	vap->va_mode = VNOVAL;
612	vap->va_nlink = VNOVAL;
613	vap->va_uid = VNOVAL;
614	vap->va_gid = VNOVAL;
615	vap->va_fsid = VNOVAL;
616	vap->va_fileid = VNOVAL;
617	vap->va_blocksize = VNOVAL;
618	vap->va_rdev = VNOVAL;
619	vap->va_atime.tv_sec = VNOVAL;
620	vap->va_atime.tv_nsec = VNOVAL;
621	vap->va_mtime.tv_sec = VNOVAL;
622	vap->va_mtime.tv_nsec = VNOVAL;
623	vap->va_ctime.tv_sec = VNOVAL;
624	vap->va_ctime.tv_nsec = VNOVAL;
625	vap->va_flags = VNOVAL;
626	vap->va_gen = VNOVAL;
627	vap->va_vaflags = 0;
628}
629
630/*
631 * This routine is called when we have too many vnodes.  It attempts
632 * to free <count> vnodes and will potentially free vnodes that still
633 * have VM backing store (VM backing store is typically the cause
634 * of a vnode blowout so we want to do this).  Therefore, this operation
635 * is not considered cheap.
636 *
637 * A number of conditions may prevent a vnode from being reclaimed.
638 * the buffer cache may have references on the vnode, a directory
639 * vnode may still have references due to the namei cache representing
640 * underlying files, or the vnode may be in active use.   It is not
641 * desireable to reuse such vnodes.  These conditions may cause the
642 * number of vnodes to reach some minimum value regardless of what
643 * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
644 */
645static int
646vlrureclaim(struct mount *mp, int count)
647{
648	struct vnode *vp;
649	int done;
650	int trigger;
651	int usevnodes;
652
653	/*
654	 * Calculate the trigger point, don't allow user
655	 * screwups to blow us up.   This prevents us from
656	 * recycling vnodes with lots of resident pages.  We
657	 * aren't trying to free memory, we are trying to
658	 * free vnodes.
659	 */
660	usevnodes = desiredvnodes;
661	if (usevnodes <= 0)
662		usevnodes = 1;
663	trigger = cnt.v_page_count * 2 / usevnodes;
664
665	done = 0;
666	mtx_lock(&mntvnode_mtx);
667	while (count && (vp = TAILQ_FIRST(&mp->mnt_nvnodelist)) != NULL) {
668		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
669		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
670
671		if (vp->v_type != VNON &&
672		    vp->v_type != VBAD &&
673		    VMIGHTFREE(vp) &&           /* critical path opt */
674		    (vp->v_object == NULL || vp->v_object->resident_page_count < trigger) &&
675		    mtx_trylock(&vp->v_interlock)
676		) {
677			mtx_unlock(&mntvnode_mtx);
678			if (VMIGHTFREE(vp)) {
679				vgonel(vp, curthread);
680				done++;
681			} else {
682				mtx_unlock(&vp->v_interlock);
683			}
684			mtx_lock(&mntvnode_mtx);
685		}
686		--count;
687	}
688	mtx_unlock(&mntvnode_mtx);
689	return done;
690}
691
692/*
693 * Attempt to recycle vnodes in a context that is always safe to block.
694 * Calling vlrurecycle() from the bowels of filesystem code has some
695 * interesting deadlock problems.
696 */
697static struct proc *vnlruproc;
698static int vnlruproc_sig;
699
700static void
701vnlru_proc(void)
702{
703	struct mount *mp, *nmp;
704	int s;
705	int done;
706	struct proc *p = vnlruproc;
707	struct thread *td = FIRST_THREAD_IN_PROC(p);	/* XXXKSE */
708
709	mtx_lock(&Giant);
710
711	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
712	    SHUTDOWN_PRI_FIRST);
713
714	s = splbio();
715	for (;;) {
716		kthread_suspend_check(p);
717		if (numvnodes - freevnodes <= desiredvnodes * 9 / 10) {
718			vnlruproc_sig = 0;
719			tsleep(vnlruproc, PVFS, "vlruwt", 0);
720			continue;
721		}
722		done = 0;
723		mtx_lock(&mountlist_mtx);
724		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
725			if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td)) {
726				nmp = TAILQ_NEXT(mp, mnt_list);
727				continue;
728			}
729			done += vlrureclaim(mp, 10);
730			mtx_lock(&mountlist_mtx);
731			nmp = TAILQ_NEXT(mp, mnt_list);
732			vfs_unbusy(mp, td);
733		}
734		mtx_unlock(&mountlist_mtx);
735		if (done == 0) {
736#if 0
737			/* These messages are temporary debugging aids */
738			if (vnlru_nowhere < 5)
739				printf("vnlru process getting nowhere..\n");
740			else if (vnlru_nowhere == 5)
741				printf("vnlru process messages stopped.\n");
742#endif
743			vnlru_nowhere++;
744			tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
745		}
746	}
747	splx(s);
748}
749
750static struct kproc_desc vnlru_kp = {
751	"vnlru",
752	vnlru_proc,
753	&vnlruproc
754};
755SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &vnlru_kp)
756
757
758/*
759 * Routines having to do with the management of the vnode table.
760 */
761
762/*
763 * Return the next vnode from the free list.
764 */
765int
766getnewvnode(tag, mp, vops, vpp)
767	enum vtagtype tag;
768	struct mount *mp;
769	vop_t **vops;
770	struct vnode **vpp;
771{
772	int s;
773	struct thread *td = curthread;	/* XXX */
774	struct vnode *vp = NULL;
775	struct mount *vnmp;
776	vm_object_t object;
777
778	s = splbio();
779	/*
780	 * Try to reuse vnodes if we hit the max.  This situation only
781	 * occurs in certain large-memory (2G+) situations.  We cannot
782	 * attempt to directly reclaim vnodes due to nasty recursion
783	 * problems.
784	 */
785	if (vnlruproc_sig == 0 && numvnodes - freevnodes > desiredvnodes) {
786		vnlruproc_sig = 1;      /* avoid unnecessary wakeups */
787		wakeup(vnlruproc);
788	}
789
790	/*
791	 * Attempt to reuse a vnode already on the free list, allocating
792	 * a new vnode if we can't find one or if we have not reached a
793	 * good minimum for good LRU performance.
794	 */
795
796	mtx_lock(&vnode_free_list_mtx);
797
798	if (freevnodes >= wantfreevnodes && numvnodes >= minvnodes) {
799		int count;
800
801		for (count = 0; count < freevnodes; count++) {
802			vp = TAILQ_FIRST(&vnode_free_list);
803			if (vp == NULL || vp->v_usecount)
804				panic("getnewvnode: free vnode isn't");
805			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
806
807			/* Don't recycle if we can't get the interlock */
808			if (!mtx_trylock(&vp->v_interlock)) {
809				vp = NULL;
810				continue;
811			}
812
813			/* We should be able to immediately acquire this */
814			if (vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE, td) != 0)
815				continue;
816			/*
817			 * Don't recycle if we still have cached pages.
818			 */
819			if (VOP_GETVOBJECT(vp, &object) == 0 &&
820			     (object->resident_page_count ||
821			      object->ref_count)) {
822				TAILQ_INSERT_TAIL(&vnode_free_list, vp,
823						    v_freelist);
824				VOP_UNLOCK(vp, 0, td);
825				vp = NULL;
826				continue;
827			}
828			if (LIST_FIRST(&vp->v_cache_src)) {
829				/*
830				 * note: nameileafonly sysctl is temporary,
831				 * for debugging only, and will eventually be
832				 * removed.
833				 */
834				if (nameileafonly > 0) {
835					/*
836					 * Do not reuse namei-cached directory
837					 * vnodes that have cached
838					 * subdirectories.
839					 */
840					if (cache_leaf_test(vp) < 0) {
841						VOP_UNLOCK(vp, 0, td);
842						TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
843						vp = NULL;
844						continue;
845					}
846				} else if (nameileafonly < 0 ||
847					    vmiodirenable == 0) {
848					/*
849					 * Do not reuse namei-cached directory
850					 * vnodes if nameileafonly is -1 or
851					 * if VMIO backing for directories is
852					 * turned off (otherwise we reuse them
853					 * too quickly).
854					 */
855					VOP_UNLOCK(vp, 0, td);
856					TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
857					vp = NULL;
858					continue;
859				}
860			}
861			/*
862			 * Skip over it if its filesystem is being suspended.
863			 */
864			if (vn_start_write(vp, &vnmp, V_NOWAIT) == 0)
865				break;
866			VOP_UNLOCK(vp, 0, td);
867			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
868			vp = NULL;
869		}
870	}
871	if (vp) {
872		vp->v_flag |= VDOOMED;
873		vp->v_flag &= ~VFREE;
874		freevnodes--;
875		mtx_unlock(&vnode_free_list_mtx);
876		cache_purge(vp);
877		if (vp->v_type != VBAD) {
878			VOP_UNLOCK(vp, 0, td);
879			vgone(vp);
880		} else {
881			VOP_UNLOCK(vp, 0, td);
882		}
883		vn_finished_write(vnmp);
884
885#ifdef INVARIANTS
886		{
887			int s;
888
889			if (vp->v_data)
890				panic("cleaned vnode isn't");
891			s = splbio();
892			if (vp->v_numoutput)
893				panic("Clean vnode has pending I/O's");
894			splx(s);
895			if (vp->v_writecount != 0)
896				panic("Non-zero write count");
897		}
898#endif
899		if (vp->v_pollinfo) {
900			mtx_destroy(&vp->v_pollinfo->vpi_lock);
901			uma_zfree(vnodepoll_zone, vp->v_pollinfo);
902		}
903		vp->v_pollinfo = NULL;
904		vp->v_flag = 0;
905		vp->v_lastw = 0;
906		vp->v_lasta = 0;
907		vp->v_cstart = 0;
908		vp->v_clen = 0;
909		vp->v_socket = 0;
910	} else {
911		mtx_unlock(&vnode_free_list_mtx);
912		vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK);
913		bzero((char *) vp, sizeof *vp);
914		mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
915		vp->v_dd = vp;
916		cache_purge(vp);
917		LIST_INIT(&vp->v_cache_src);
918		TAILQ_INIT(&vp->v_cache_dst);
919		numvnodes++;
920	}
921
922	TAILQ_INIT(&vp->v_cleanblkhd);
923	TAILQ_INIT(&vp->v_dirtyblkhd);
924	vp->v_type = VNON;
925	vp->v_tag = tag;
926	vp->v_op = vops;
927	lockinit(&vp->v_lock, PVFS, "vnlock", VLKTIMEOUT, LK_NOPAUSE);
928	insmntque(vp, mp);
929	*vpp = vp;
930	vp->v_usecount = 1;
931	vp->v_data = 0;
932
933	splx(s);
934
935#if 0
936	vnodeallocs++;
937	if (vnodeallocs % vnoderecycleperiod == 0 &&
938	    freevnodes < vnoderecycleminfreevn &&
939	    vnoderecyclemintotalvn < numvnodes) {
940		/* Recycle vnodes. */
941		cache_purgeleafdirs(vnoderecyclenumber);
942	}
943#endif
944
945	return (0);
946}
947
948/*
949 * Move a vnode from one mount queue to another.
950 */
951static void
952insmntque(vp, mp)
953	register struct vnode *vp;
954	register struct mount *mp;
955{
956
957	mtx_lock(&mntvnode_mtx);
958	/*
959	 * Delete from old mount point vnode list, if on one.
960	 */
961	if (vp->v_mount != NULL)
962		TAILQ_REMOVE(&vp->v_mount->mnt_nvnodelist, vp, v_nmntvnodes);
963	/*
964	 * Insert into list of vnodes for the new mount point, if available.
965	 */
966	if ((vp->v_mount = mp) == NULL) {
967		mtx_unlock(&mntvnode_mtx);
968		return;
969	}
970	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
971	mtx_unlock(&mntvnode_mtx);
972}
973
974/*
975 * Update outstanding I/O count and do wakeup if requested.
976 */
977void
978vwakeup(bp)
979	register struct buf *bp;
980{
981	register struct vnode *vp;
982
983	bp->b_flags &= ~B_WRITEINPROG;
984	if ((vp = bp->b_vp)) {
985		vp->v_numoutput--;
986		if (vp->v_numoutput < 0)
987			panic("vwakeup: neg numoutput");
988		if ((vp->v_numoutput == 0) && (vp->v_flag & VBWAIT)) {
989			vp->v_flag &= ~VBWAIT;
990			wakeup(&vp->v_numoutput);
991		}
992	}
993}
994
995/*
996 * Flush out and invalidate all buffers associated with a vnode.
997 * Called with the underlying object locked.
998 */
999int
1000vinvalbuf(vp, flags, cred, td, slpflag, slptimeo)
1001	register struct vnode *vp;
1002	int flags;
1003	struct ucred *cred;
1004	struct thread *td;
1005	int slpflag, slptimeo;
1006{
1007	register struct buf *bp;
1008	struct buf *nbp, *blist;
1009	int s, error;
1010	vm_object_t object;
1011
1012	GIANT_REQUIRED;
1013
1014	if (flags & V_SAVE) {
1015		s = splbio();
1016		while (vp->v_numoutput) {
1017			vp->v_flag |= VBWAIT;
1018			error = tsleep(&vp->v_numoutput,
1019			    slpflag | (PRIBIO + 1), "vinvlbuf", slptimeo);
1020			if (error) {
1021				splx(s);
1022				return (error);
1023			}
1024		}
1025		if (!TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
1026			splx(s);
1027			if ((error = VOP_FSYNC(vp, cred, MNT_WAIT, td)) != 0)
1028				return (error);
1029			s = splbio();
1030			if (vp->v_numoutput > 0 ||
1031			    !TAILQ_EMPTY(&vp->v_dirtyblkhd))
1032				panic("vinvalbuf: dirty bufs");
1033		}
1034		splx(s);
1035	}
1036	s = splbio();
1037	for (;;) {
1038		blist = TAILQ_FIRST(&vp->v_cleanblkhd);
1039		if (!blist)
1040			blist = TAILQ_FIRST(&vp->v_dirtyblkhd);
1041		if (!blist)
1042			break;
1043
1044		for (bp = blist; bp; bp = nbp) {
1045			nbp = TAILQ_NEXT(bp, b_vnbufs);
1046			if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
1047				error = BUF_TIMELOCK(bp,
1048				    LK_EXCLUSIVE | LK_SLEEPFAIL,
1049				    "vinvalbuf", slpflag, slptimeo);
1050				if (error == ENOLCK)
1051					break;
1052				splx(s);
1053				return (error);
1054			}
1055			/*
1056			 * XXX Since there are no node locks for NFS, I
1057			 * believe there is a slight chance that a delayed
1058			 * write will occur while sleeping just above, so
1059			 * check for it.  Note that vfs_bio_awrite expects
1060			 * buffers to reside on a queue, while BUF_WRITE and
1061			 * brelse do not.
1062			 */
1063			if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1064				(flags & V_SAVE)) {
1065
1066				if (bp->b_vp == vp) {
1067					if (bp->b_flags & B_CLUSTEROK) {
1068						BUF_UNLOCK(bp);
1069						vfs_bio_awrite(bp);
1070					} else {
1071						bremfree(bp);
1072						bp->b_flags |= B_ASYNC;
1073						BUF_WRITE(bp);
1074					}
1075				} else {
1076					bremfree(bp);
1077					(void) BUF_WRITE(bp);
1078				}
1079				break;
1080			}
1081			bremfree(bp);
1082			bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
1083			bp->b_flags &= ~B_ASYNC;
1084			brelse(bp);
1085		}
1086	}
1087
1088	/*
1089	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1090	 * have write I/O in-progress but if there is a VM object then the
1091	 * VM object can also have read-I/O in-progress.
1092	 */
1093	do {
1094		while (vp->v_numoutput > 0) {
1095			vp->v_flag |= VBWAIT;
1096			tsleep(&vp->v_numoutput, PVM, "vnvlbv", 0);
1097		}
1098		if (VOP_GETVOBJECT(vp, &object) == 0) {
1099			while (object->paging_in_progress)
1100			vm_object_pip_sleep(object, "vnvlbx");
1101		}
1102	} while (vp->v_numoutput > 0);
1103
1104	splx(s);
1105
1106	/*
1107	 * Destroy the copy in the VM cache, too.
1108	 */
1109	mtx_lock(&vp->v_interlock);
1110	if (VOP_GETVOBJECT(vp, &object) == 0) {
1111		vm_object_page_remove(object, 0, 0,
1112			(flags & V_SAVE) ? TRUE : FALSE);
1113	}
1114	mtx_unlock(&vp->v_interlock);
1115
1116	if (!TAILQ_EMPTY(&vp->v_dirtyblkhd) || !TAILQ_EMPTY(&vp->v_cleanblkhd))
1117		panic("vinvalbuf: flush failed");
1118	return (0);
1119}
1120
1121/*
1122 * Truncate a file's buffer and pages to a specified length.  This
1123 * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1124 * sync activity.
1125 */
1126int
1127vtruncbuf(vp, cred, td, length, blksize)
1128	register struct vnode *vp;
1129	struct ucred *cred;
1130	struct thread *td;
1131	off_t length;
1132	int blksize;
1133{
1134	register struct buf *bp;
1135	struct buf *nbp;
1136	int s, anyfreed;
1137	int trunclbn;
1138
1139	/*
1140	 * Round up to the *next* lbn.
1141	 */
1142	trunclbn = (length + blksize - 1) / blksize;
1143
1144	s = splbio();
1145restart:
1146	anyfreed = 1;
1147	for (;anyfreed;) {
1148		anyfreed = 0;
1149		for (bp = TAILQ_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
1150			nbp = TAILQ_NEXT(bp, b_vnbufs);
1151			if (bp->b_lblkno >= trunclbn) {
1152				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
1153					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
1154					goto restart;
1155				} else {
1156					bremfree(bp);
1157					bp->b_flags |= (B_INVAL | B_RELBUF);
1158					bp->b_flags &= ~B_ASYNC;
1159					brelse(bp);
1160					anyfreed = 1;
1161				}
1162				if (nbp &&
1163				    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1164				    (nbp->b_vp != vp) ||
1165				    (nbp->b_flags & B_DELWRI))) {
1166					goto restart;
1167				}
1168			}
1169		}
1170
1171		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
1172			nbp = TAILQ_NEXT(bp, b_vnbufs);
1173			if (bp->b_lblkno >= trunclbn) {
1174				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
1175					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
1176					goto restart;
1177				} else {
1178					bremfree(bp);
1179					bp->b_flags |= (B_INVAL | B_RELBUF);
1180					bp->b_flags &= ~B_ASYNC;
1181					brelse(bp);
1182					anyfreed = 1;
1183				}
1184				if (nbp &&
1185				    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1186				    (nbp->b_vp != vp) ||
1187				    (nbp->b_flags & B_DELWRI) == 0)) {
1188					goto restart;
1189				}
1190			}
1191		}
1192	}
1193
1194	if (length > 0) {
1195restartsync:
1196		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
1197			nbp = TAILQ_NEXT(bp, b_vnbufs);
1198			if ((bp->b_flags & B_DELWRI) && (bp->b_lblkno < 0)) {
1199				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
1200					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
1201					goto restart;
1202				} else {
1203					bremfree(bp);
1204					if (bp->b_vp == vp) {
1205						bp->b_flags |= B_ASYNC;
1206					} else {
1207						bp->b_flags &= ~B_ASYNC;
1208					}
1209					BUF_WRITE(bp);
1210				}
1211				goto restartsync;
1212			}
1213
1214		}
1215	}
1216
1217	while (vp->v_numoutput > 0) {
1218		vp->v_flag |= VBWAIT;
1219		tsleep(&vp->v_numoutput, PVM, "vbtrunc", 0);
1220	}
1221
1222	splx(s);
1223
1224	vnode_pager_setsize(vp, length);
1225
1226	return (0);
1227}
1228
1229/*
1230 * Associate a buffer with a vnode.
1231 */
1232void
1233bgetvp(vp, bp)
1234	register struct vnode *vp;
1235	register struct buf *bp;
1236{
1237	int s;
1238
1239	KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
1240
1241	vhold(vp);
1242	bp->b_vp = vp;
1243	bp->b_dev = vn_todev(vp);
1244	/*
1245	 * Insert onto list for new vnode.
1246	 */
1247	s = splbio();
1248	bp->b_xflags |= BX_VNCLEAN;
1249	bp->b_xflags &= ~BX_VNDIRTY;
1250	TAILQ_INSERT_TAIL(&vp->v_cleanblkhd, bp, b_vnbufs);
1251	splx(s);
1252}
1253
1254/*
1255 * Disassociate a buffer from a vnode.
1256 */
1257void
1258brelvp(bp)
1259	register struct buf *bp;
1260{
1261	struct vnode *vp;
1262	struct buflists *listheadp;
1263	int s;
1264
1265	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1266
1267	/*
1268	 * Delete from old vnode list, if on one.
1269	 */
1270	vp = bp->b_vp;
1271	s = splbio();
1272	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1273		if (bp->b_xflags & BX_VNDIRTY)
1274			listheadp = &vp->v_dirtyblkhd;
1275		else
1276			listheadp = &vp->v_cleanblkhd;
1277		TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1278		bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1279	}
1280	if ((vp->v_flag & VONWORKLST) && TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
1281		vp->v_flag &= ~VONWORKLST;
1282		LIST_REMOVE(vp, v_synclist);
1283	}
1284	splx(s);
1285	bp->b_vp = (struct vnode *) 0;
1286	vdrop(vp);
1287}
1288
1289/*
1290 * Add an item to the syncer work queue.
1291 */
1292static void
1293vn_syncer_add_to_worklist(struct vnode *vp, int delay)
1294{
1295	int s, slot;
1296
1297	s = splbio();
1298
1299	if (vp->v_flag & VONWORKLST) {
1300		LIST_REMOVE(vp, v_synclist);
1301	}
1302
1303	if (delay > syncer_maxdelay - 2)
1304		delay = syncer_maxdelay - 2;
1305	slot = (syncer_delayno + delay) & syncer_mask;
1306
1307	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], vp, v_synclist);
1308	vp->v_flag |= VONWORKLST;
1309	splx(s);
1310}
1311
1312struct  proc *updateproc;
1313static void sched_sync(void);
1314static struct kproc_desc up_kp = {
1315	"syncer",
1316	sched_sync,
1317	&updateproc
1318};
1319SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
1320
1321/*
1322 * System filesystem synchronizer daemon.
1323 */
1324void
1325sched_sync(void)
1326{
1327	struct synclist *slp;
1328	struct vnode *vp;
1329	struct mount *mp;
1330	long starttime;
1331	int s;
1332	struct thread *td = FIRST_THREAD_IN_PROC(updateproc);  /* XXXKSE */
1333
1334	mtx_lock(&Giant);
1335
1336	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, td->td_proc,
1337	    SHUTDOWN_PRI_LAST);
1338
1339	for (;;) {
1340		kthread_suspend_check(td->td_proc);
1341
1342		starttime = time_second;
1343
1344		/*
1345		 * Push files whose dirty time has expired.  Be careful
1346		 * of interrupt race on slp queue.
1347		 */
1348		s = splbio();
1349		slp = &syncer_workitem_pending[syncer_delayno];
1350		syncer_delayno += 1;
1351		if (syncer_delayno == syncer_maxdelay)
1352			syncer_delayno = 0;
1353		splx(s);
1354
1355		while ((vp = LIST_FIRST(slp)) != NULL) {
1356			if (VOP_ISLOCKED(vp, NULL) == 0 &&
1357			    vn_start_write(vp, &mp, V_NOWAIT) == 0) {
1358				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, td);
1359				(void) VOP_FSYNC(vp, td->td_ucred, MNT_LAZY, td);
1360				VOP_UNLOCK(vp, 0, td);
1361				vn_finished_write(mp);
1362			}
1363			s = splbio();
1364			if (LIST_FIRST(slp) == vp) {
1365				/*
1366				 * Note: v_tag VT_VFS vps can remain on the
1367				 * worklist too with no dirty blocks, but
1368				 * since sync_fsync() moves it to a different
1369				 * slot we are safe.
1370				 */
1371				if (TAILQ_EMPTY(&vp->v_dirtyblkhd) &&
1372				    !vn_isdisk(vp, NULL))
1373					panic("sched_sync: fsync failed vp %p tag %d", vp, vp->v_tag);
1374				/*
1375				 * Put us back on the worklist.  The worklist
1376				 * routine will remove us from our current
1377				 * position and then add us back in at a later
1378				 * position.
1379				 */
1380				vn_syncer_add_to_worklist(vp, syncdelay);
1381			}
1382			splx(s);
1383		}
1384
1385		/*
1386		 * Do soft update processing.
1387		 */
1388		if (softdep_process_worklist_hook != NULL)
1389			(*softdep_process_worklist_hook)(NULL);
1390
1391		/*
1392		 * The variable rushjob allows the kernel to speed up the
1393		 * processing of the filesystem syncer process. A rushjob
1394		 * value of N tells the filesystem syncer to process the next
1395		 * N seconds worth of work on its queue ASAP. Currently rushjob
1396		 * is used by the soft update code to speed up the filesystem
1397		 * syncer process when the incore state is getting so far
1398		 * ahead of the disk that the kernel memory pool is being
1399		 * threatened with exhaustion.
1400		 */
1401		if (rushjob > 0) {
1402			rushjob -= 1;
1403			continue;
1404		}
1405		/*
1406		 * If it has taken us less than a second to process the
1407		 * current work, then wait. Otherwise start right over
1408		 * again. We can still lose time if any single round
1409		 * takes more than two seconds, but it does not really
1410		 * matter as we are just trying to generally pace the
1411		 * filesystem activity.
1412		 */
1413		if (time_second == starttime)
1414			tsleep(&lbolt, PPAUSE, "syncer", 0);
1415	}
1416}
1417
1418/*
1419 * Request the syncer daemon to speed up its work.
1420 * We never push it to speed up more than half of its
1421 * normal turn time, otherwise it could take over the cpu.
1422 * XXXKSE  only one update?
1423 */
1424int
1425speedup_syncer()
1426{
1427
1428	mtx_lock_spin(&sched_lock);
1429	if (FIRST_THREAD_IN_PROC(updateproc)->td_wchan == &lbolt) /* XXXKSE */
1430		setrunnable(FIRST_THREAD_IN_PROC(updateproc));
1431	mtx_unlock_spin(&sched_lock);
1432	if (rushjob < syncdelay / 2) {
1433		rushjob += 1;
1434		stat_rush_requests += 1;
1435		return (1);
1436	}
1437	return(0);
1438}
1439
1440/*
1441 * Associate a p-buffer with a vnode.
1442 *
1443 * Also sets B_PAGING flag to indicate that vnode is not fully associated
1444 * with the buffer.  i.e. the bp has not been linked into the vnode or
1445 * ref-counted.
1446 */
1447void
1448pbgetvp(vp, bp)
1449	register struct vnode *vp;
1450	register struct buf *bp;
1451{
1452
1453	KASSERT(bp->b_vp == NULL, ("pbgetvp: not free"));
1454
1455	bp->b_vp = vp;
1456	bp->b_flags |= B_PAGING;
1457	bp->b_dev = vn_todev(vp);
1458}
1459
1460/*
1461 * Disassociate a p-buffer from a vnode.
1462 */
1463void
1464pbrelvp(bp)
1465	register struct buf *bp;
1466{
1467
1468	KASSERT(bp->b_vp != NULL, ("pbrelvp: NULL"));
1469
1470	/* XXX REMOVE ME */
1471	if (TAILQ_NEXT(bp, b_vnbufs) != NULL) {
1472		panic(
1473		    "relpbuf(): b_vp was probably reassignbuf()d %p %x",
1474		    bp,
1475		    (int)bp->b_flags
1476		);
1477	}
1478	bp->b_vp = (struct vnode *) 0;
1479	bp->b_flags &= ~B_PAGING;
1480}
1481
1482/*
1483 * Reassign a buffer from one vnode to another.
1484 * Used to assign file specific control information
1485 * (indirect blocks) to the vnode to which they belong.
1486 */
1487void
1488reassignbuf(bp, newvp)
1489	register struct buf *bp;
1490	register struct vnode *newvp;
1491{
1492	struct buflists *listheadp;
1493	int delay;
1494	int s;
1495
1496	if (newvp == NULL) {
1497		printf("reassignbuf: NULL");
1498		return;
1499	}
1500	++reassignbufcalls;
1501
1502	/*
1503	 * B_PAGING flagged buffers cannot be reassigned because their vp
1504	 * is not fully linked in.
1505	 */
1506	if (bp->b_flags & B_PAGING)
1507		panic("cannot reassign paging buffer");
1508
1509	s = splbio();
1510	/*
1511	 * Delete from old vnode list, if on one.
1512	 */
1513	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN)) {
1514		if (bp->b_xflags & BX_VNDIRTY)
1515			listheadp = &bp->b_vp->v_dirtyblkhd;
1516		else
1517			listheadp = &bp->b_vp->v_cleanblkhd;
1518		TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1519		bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1520		if (bp->b_vp != newvp) {
1521			vdrop(bp->b_vp);
1522			bp->b_vp = NULL;	/* for clarification */
1523		}
1524	}
1525	/*
1526	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1527	 * of clean buffers.
1528	 */
1529	if (bp->b_flags & B_DELWRI) {
1530		struct buf *tbp;
1531
1532		listheadp = &newvp->v_dirtyblkhd;
1533		if ((newvp->v_flag & VONWORKLST) == 0) {
1534			switch (newvp->v_type) {
1535			case VDIR:
1536				delay = dirdelay;
1537				break;
1538			case VCHR:
1539				if (newvp->v_rdev->si_mountpoint != NULL) {
1540					delay = metadelay;
1541					break;
1542				}
1543				/* fall through */
1544			default:
1545				delay = filedelay;
1546			}
1547			vn_syncer_add_to_worklist(newvp, delay);
1548		}
1549		bp->b_xflags |= BX_VNDIRTY;
1550		tbp = TAILQ_FIRST(listheadp);
1551		if (tbp == NULL ||
1552		    bp->b_lblkno == 0 ||
1553		    (bp->b_lblkno > 0 && tbp->b_lblkno < 0) ||
1554		    (bp->b_lblkno > 0 && bp->b_lblkno < tbp->b_lblkno)) {
1555			TAILQ_INSERT_HEAD(listheadp, bp, b_vnbufs);
1556			++reassignbufsortgood;
1557		} else if (bp->b_lblkno < 0) {
1558			TAILQ_INSERT_TAIL(listheadp, bp, b_vnbufs);
1559			++reassignbufsortgood;
1560		} else if (reassignbufmethod == 1) {
1561			/*
1562			 * New sorting algorithm, only handle sequential case,
1563			 * otherwise append to end (but before metadata)
1564			 */
1565			if ((tbp = gbincore(newvp, bp->b_lblkno - 1)) != NULL &&
1566			    (tbp->b_xflags & BX_VNDIRTY)) {
1567				/*
1568				 * Found the best place to insert the buffer
1569				 */
1570				TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1571				++reassignbufsortgood;
1572			} else {
1573				/*
1574				 * Missed, append to end, but before meta-data.
1575				 * We know that the head buffer in the list is
1576				 * not meta-data due to prior conditionals.
1577				 *
1578				 * Indirect effects:  NFS second stage write
1579				 * tends to wind up here, giving maximum
1580				 * distance between the unstable write and the
1581				 * commit rpc.
1582				 */
1583				tbp = TAILQ_LAST(listheadp, buflists);
1584				while (tbp && tbp->b_lblkno < 0)
1585					tbp = TAILQ_PREV(tbp, buflists, b_vnbufs);
1586				TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1587				++reassignbufsortbad;
1588			}
1589		} else {
1590			/*
1591			 * Old sorting algorithm, scan queue and insert
1592			 */
1593			struct buf *ttbp;
1594			while ((ttbp = TAILQ_NEXT(tbp, b_vnbufs)) &&
1595			    (ttbp->b_lblkno < bp->b_lblkno)) {
1596				++reassignbufloops;
1597				tbp = ttbp;
1598			}
1599			TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1600		}
1601	} else {
1602		bp->b_xflags |= BX_VNCLEAN;
1603		TAILQ_INSERT_TAIL(&newvp->v_cleanblkhd, bp, b_vnbufs);
1604		if ((newvp->v_flag & VONWORKLST) &&
1605		    TAILQ_EMPTY(&newvp->v_dirtyblkhd)) {
1606			newvp->v_flag &= ~VONWORKLST;
1607			LIST_REMOVE(newvp, v_synclist);
1608		}
1609	}
1610	if (bp->b_vp != newvp) {
1611		bp->b_vp = newvp;
1612		vhold(bp->b_vp);
1613	}
1614	splx(s);
1615}
1616
1617/*
1618 * Create a vnode for a device.
1619 * Used for mounting the root filesystem.
1620 */
1621int
1622bdevvp(dev, vpp)
1623	dev_t dev;
1624	struct vnode **vpp;
1625{
1626	register struct vnode *vp;
1627	struct vnode *nvp;
1628	int error;
1629
1630	if (dev == NODEV) {
1631		*vpp = NULLVP;
1632		return (ENXIO);
1633	}
1634	if (vfinddev(dev, VCHR, vpp))
1635		return (0);
1636	error = getnewvnode(VT_NON, (struct mount *)0, spec_vnodeop_p, &nvp);
1637	if (error) {
1638		*vpp = NULLVP;
1639		return (error);
1640	}
1641	vp = nvp;
1642	vp->v_type = VCHR;
1643	addalias(vp, dev);
1644	*vpp = vp;
1645	return (0);
1646}
1647
1648/*
1649 * Add vnode to the alias list hung off the dev_t.
1650 *
1651 * The reason for this gunk is that multiple vnodes can reference
1652 * the same physical device, so checking vp->v_usecount to see
1653 * how many users there are is inadequate; the v_usecount for
1654 * the vnodes need to be accumulated.  vcount() does that.
1655 */
1656struct vnode *
1657addaliasu(nvp, nvp_rdev)
1658	struct vnode *nvp;
1659	udev_t nvp_rdev;
1660{
1661	struct vnode *ovp;
1662	vop_t **ops;
1663	dev_t dev;
1664
1665	if (nvp->v_type == VBLK)
1666		return (nvp);
1667	if (nvp->v_type != VCHR)
1668		panic("addaliasu on non-special vnode");
1669	dev = udev2dev(nvp_rdev, 0);
1670	/*
1671	 * Check to see if we have a bdevvp vnode with no associated
1672	 * filesystem. If so, we want to associate the filesystem of
1673	 * the new newly instigated vnode with the bdevvp vnode and
1674	 * discard the newly created vnode rather than leaving the
1675	 * bdevvp vnode lying around with no associated filesystem.
1676	 */
1677	if (vfinddev(dev, nvp->v_type, &ovp) == 0 || ovp->v_data != NULL) {
1678		addalias(nvp, dev);
1679		return (nvp);
1680	}
1681	/*
1682	 * Discard unneeded vnode, but save its node specific data.
1683	 * Note that if there is a lock, it is carried over in the
1684	 * node specific data to the replacement vnode.
1685	 */
1686	vref(ovp);
1687	ovp->v_data = nvp->v_data;
1688	ovp->v_tag = nvp->v_tag;
1689	nvp->v_data = NULL;
1690	lockinit(&ovp->v_lock, PVFS, nvp->v_lock.lk_wmesg,
1691	    nvp->v_lock.lk_timo, nvp->v_lock.lk_flags & LK_EXTFLG_MASK);
1692	if (nvp->v_vnlock)
1693		ovp->v_vnlock = &ovp->v_lock;
1694	ops = ovp->v_op;
1695	ovp->v_op = nvp->v_op;
1696	if (VOP_ISLOCKED(nvp, curthread)) {
1697		VOP_UNLOCK(nvp, 0, curthread);
1698		vn_lock(ovp, LK_EXCLUSIVE | LK_RETRY, curthread);
1699	}
1700	nvp->v_op = ops;
1701	insmntque(ovp, nvp->v_mount);
1702	vrele(nvp);
1703	vgone(nvp);
1704	return (ovp);
1705}
1706
1707/* This is a local helper function that do the same as addaliasu, but for a
1708 * dev_t instead of an udev_t. */
1709static void
1710addalias(nvp, dev)
1711	struct vnode *nvp;
1712	dev_t dev;
1713{
1714
1715	KASSERT(nvp->v_type == VCHR, ("addalias on non-special vnode"));
1716	nvp->v_rdev = dev;
1717	mtx_lock(&spechash_mtx);
1718	SLIST_INSERT_HEAD(&dev->si_hlist, nvp, v_specnext);
1719	mtx_unlock(&spechash_mtx);
1720}
1721
1722/*
1723 * Grab a particular vnode from the free list, increment its
1724 * reference count and lock it. The vnode lock bit is set if the
1725 * vnode is being eliminated in vgone. The process is awakened
1726 * when the transition is completed, and an error returned to
1727 * indicate that the vnode is no longer usable (possibly having
1728 * been changed to a new filesystem type).
1729 */
1730int
1731vget(vp, flags, td)
1732	register struct vnode *vp;
1733	int flags;
1734	struct thread *td;
1735{
1736	int error;
1737
1738	/*
1739	 * If the vnode is in the process of being cleaned out for
1740	 * another use, we wait for the cleaning to finish and then
1741	 * return failure. Cleaning is determined by checking that
1742	 * the VXLOCK flag is set.
1743	 */
1744	if ((flags & LK_INTERLOCK) == 0)
1745		mtx_lock(&vp->v_interlock);
1746	if (vp->v_flag & VXLOCK) {
1747		if (vp->v_vxproc == curthread) {
1748#if 0
1749			/* this can now occur in normal operation */
1750			log(LOG_INFO, "VXLOCK interlock avoided\n");
1751#endif
1752		} else {
1753			vp->v_flag |= VXWANT;
1754			msleep(vp, &vp->v_interlock, PINOD | PDROP, "vget", 0);
1755			return (ENOENT);
1756		}
1757	}
1758
1759	vp->v_usecount++;
1760
1761	if (VSHOULDBUSY(vp))
1762		vbusy(vp);
1763	if (flags & LK_TYPE_MASK) {
1764		if ((error = vn_lock(vp, flags | LK_INTERLOCK, td)) != 0) {
1765			/*
1766			 * must expand vrele here because we do not want
1767			 * to call VOP_INACTIVE if the reference count
1768			 * drops back to zero since it was never really
1769			 * active. We must remove it from the free list
1770			 * before sleeping so that multiple processes do
1771			 * not try to recycle it.
1772			 */
1773			mtx_lock(&vp->v_interlock);
1774			vp->v_usecount--;
1775			if (VSHOULDFREE(vp))
1776				vfree(vp);
1777			else
1778				vlruvp(vp);
1779			mtx_unlock(&vp->v_interlock);
1780		}
1781		return (error);
1782	}
1783	mtx_unlock(&vp->v_interlock);
1784	return (0);
1785}
1786
1787/*
1788 * Increase the reference count of a vnode.
1789 */
1790void
1791vref(struct vnode *vp)
1792{
1793	mtx_lock(&vp->v_interlock);
1794	vp->v_usecount++;
1795	mtx_unlock(&vp->v_interlock);
1796}
1797
1798/*
1799 * Vnode put/release.
1800 * If count drops to zero, call inactive routine and return to freelist.
1801 */
1802void
1803vrele(vp)
1804	struct vnode *vp;
1805{
1806	struct thread *td = curthread;	/* XXX */
1807
1808	KASSERT(vp != NULL, ("vrele: null vp"));
1809
1810	mtx_lock(&vp->v_interlock);
1811
1812	/* Skip this v_writecount check if we're going to panic below. */
1813	KASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1,
1814	    ("vrele: missed vn_close"));
1815
1816	if (vp->v_usecount > 1) {
1817
1818		vp->v_usecount--;
1819		mtx_unlock(&vp->v_interlock);
1820
1821		return;
1822	}
1823
1824	if (vp->v_usecount == 1) {
1825		vp->v_usecount--;
1826		/*
1827		 * We must call VOP_INACTIVE with the node locked.
1828		 * If we are doing a vput, the node is already locked,
1829		 * but, in the case of vrele, we must explicitly lock
1830		 * the vnode before calling VOP_INACTIVE.
1831		 */
1832		if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, td) == 0)
1833			VOP_INACTIVE(vp, td);
1834		if (VSHOULDFREE(vp))
1835			vfree(vp);
1836		else
1837			vlruvp(vp);
1838
1839	} else {
1840#ifdef DIAGNOSTIC
1841		vprint("vrele: negative ref count", vp);
1842		mtx_unlock(&vp->v_interlock);
1843#endif
1844		panic("vrele: negative ref cnt");
1845	}
1846}
1847
1848/*
1849 * Release an already locked vnode.  This give the same effects as
1850 * unlock+vrele(), but takes less time and avoids releasing and
1851 * re-aquiring the lock (as vrele() aquires the lock internally.)
1852 */
1853void
1854vput(vp)
1855	struct vnode *vp;
1856{
1857	struct thread *td = curthread;	/* XXX */
1858
1859	GIANT_REQUIRED;
1860
1861	KASSERT(vp != NULL, ("vput: null vp"));
1862	mtx_lock(&vp->v_interlock);
1863	/* Skip this v_writecount check if we're going to panic below. */
1864	KASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1,
1865	    ("vput: missed vn_close"));
1866
1867	if (vp->v_usecount > 1) {
1868		vp->v_usecount--;
1869		VOP_UNLOCK(vp, LK_INTERLOCK, td);
1870		return;
1871	}
1872
1873	if (vp->v_usecount == 1) {
1874		vp->v_usecount--;
1875		/*
1876		 * We must call VOP_INACTIVE with the node locked.
1877		 * If we are doing a vput, the node is already locked,
1878		 * so we just need to release the vnode mutex.
1879		 */
1880		mtx_unlock(&vp->v_interlock);
1881		VOP_INACTIVE(vp, td);
1882		if (VSHOULDFREE(vp))
1883			vfree(vp);
1884		else
1885			vlruvp(vp);
1886
1887	} else {
1888#ifdef DIAGNOSTIC
1889		vprint("vput: negative ref count", vp);
1890#endif
1891		panic("vput: negative ref cnt");
1892	}
1893}
1894
1895/*
1896 * Somebody doesn't want the vnode recycled.
1897 */
1898void
1899vhold(vp)
1900	register struct vnode *vp;
1901{
1902	int s;
1903
1904	s = splbio();
1905	vp->v_holdcnt++;
1906	if (VSHOULDBUSY(vp))
1907		vbusy(vp);
1908	splx(s);
1909}
1910
1911/*
1912 * Note that there is one less who cares about this vnode.  vdrop() is the
1913 * opposite of vhold().
1914 */
1915void
1916vdrop(vp)
1917	register struct vnode *vp;
1918{
1919	int s;
1920
1921	s = splbio();
1922	if (vp->v_holdcnt <= 0)
1923		panic("vdrop: holdcnt");
1924	vp->v_holdcnt--;
1925	if (VSHOULDFREE(vp))
1926		vfree(vp);
1927	else
1928		vlruvp(vp);
1929	splx(s);
1930}
1931
1932/*
1933 * Remove any vnodes in the vnode table belonging to mount point mp.
1934 *
1935 * If FORCECLOSE is not specified, there should not be any active ones,
1936 * return error if any are found (nb: this is a user error, not a
1937 * system error). If FORCECLOSE is specified, detach any active vnodes
1938 * that are found.
1939 *
1940 * If WRITECLOSE is set, only flush out regular file vnodes open for
1941 * writing.
1942 *
1943 * SKIPSYSTEM causes any vnodes marked VSYSTEM to be skipped.
1944 *
1945 * `rootrefs' specifies the base reference count for the root vnode
1946 * of this filesystem. The root vnode is considered busy if its
1947 * v_usecount exceeds this value. On a successful return, vflush()
1948 * will call vrele() on the root vnode exactly rootrefs times.
1949 * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
1950 * be zero.
1951 */
1952#ifdef DIAGNOSTIC
1953static int busyprt = 0;		/* print out busy vnodes */
1954SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
1955#endif
1956
1957int
1958vflush(mp, rootrefs, flags)
1959	struct mount *mp;
1960	int rootrefs;
1961	int flags;
1962{
1963	struct thread *td = curthread;	/* XXX */
1964	struct vnode *vp, *nvp, *rootvp = NULL;
1965	struct vattr vattr;
1966	int busy = 0, error;
1967
1968	if (rootrefs > 0) {
1969		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
1970		    ("vflush: bad args"));
1971		/*
1972		 * Get the filesystem root vnode. We can vput() it
1973		 * immediately, since with rootrefs > 0, it won't go away.
1974		 */
1975		if ((error = VFS_ROOT(mp, &rootvp)) != 0)
1976			return (error);
1977		vput(rootvp);
1978	}
1979	mtx_lock(&mntvnode_mtx);
1980loop:
1981	for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp; vp = nvp) {
1982		/*
1983		 * Make sure this vnode wasn't reclaimed in getnewvnode().
1984		 * Start over if it has (it won't be on the list anymore).
1985		 */
1986		if (vp->v_mount != mp)
1987			goto loop;
1988		nvp = TAILQ_NEXT(vp, v_nmntvnodes);
1989
1990		mtx_unlock(&mntvnode_mtx);
1991		mtx_lock(&vp->v_interlock);
1992		/*
1993		 * Skip over a vnodes marked VSYSTEM.
1994		 */
1995		if ((flags & SKIPSYSTEM) && (vp->v_flag & VSYSTEM)) {
1996			mtx_unlock(&vp->v_interlock);
1997			mtx_lock(&mntvnode_mtx);
1998			continue;
1999		}
2000		/*
2001		 * If WRITECLOSE is set, flush out unlinked but still open
2002		 * files (even if open only for reading) and regular file
2003		 * vnodes open for writing.
2004		 */
2005		if ((flags & WRITECLOSE) &&
2006		    (vp->v_type == VNON ||
2007		    (VOP_GETATTR(vp, &vattr, td->td_ucred, td) == 0 &&
2008		    vattr.va_nlink > 0)) &&
2009		    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2010			mtx_unlock(&vp->v_interlock);
2011			mtx_lock(&mntvnode_mtx);
2012			continue;
2013		}
2014
2015		/*
2016		 * With v_usecount == 0, all we need to do is clear out the
2017		 * vnode data structures and we are done.
2018		 */
2019		if (vp->v_usecount == 0) {
2020			vgonel(vp, td);
2021			mtx_lock(&mntvnode_mtx);
2022			continue;
2023		}
2024
2025		/*
2026		 * If FORCECLOSE is set, forcibly close the vnode. For block
2027		 * or character devices, revert to an anonymous device. For
2028		 * all other files, just kill them.
2029		 */
2030		if (flags & FORCECLOSE) {
2031			if (vp->v_type != VCHR) {
2032				vgonel(vp, td);
2033			} else {
2034				vclean(vp, 0, td);
2035				vp->v_op = spec_vnodeop_p;
2036				insmntque(vp, (struct mount *) 0);
2037			}
2038			mtx_lock(&mntvnode_mtx);
2039			continue;
2040		}
2041#ifdef DIAGNOSTIC
2042		if (busyprt)
2043			vprint("vflush: busy vnode", vp);
2044#endif
2045		mtx_unlock(&vp->v_interlock);
2046		mtx_lock(&mntvnode_mtx);
2047		busy++;
2048	}
2049	mtx_unlock(&mntvnode_mtx);
2050	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2051		/*
2052		 * If just the root vnode is busy, and if its refcount
2053		 * is equal to `rootrefs', then go ahead and kill it.
2054		 */
2055		mtx_lock(&rootvp->v_interlock);
2056		KASSERT(busy > 0, ("vflush: not busy"));
2057		KASSERT(rootvp->v_usecount >= rootrefs, ("vflush: rootrefs"));
2058		if (busy == 1 && rootvp->v_usecount == rootrefs) {
2059			vgonel(rootvp, td);
2060			busy = 0;
2061		} else
2062			mtx_unlock(&rootvp->v_interlock);
2063	}
2064	if (busy)
2065		return (EBUSY);
2066	for (; rootrefs > 0; rootrefs--)
2067		vrele(rootvp);
2068	return (0);
2069}
2070
2071/*
2072 * This moves a now (likely recyclable) vnode to the end of the
2073 * mountlist.  XXX However, it is temporarily disabled until we
2074 * can clean up ffs_sync() and friends, which have loop restart
2075 * conditions which this code causes to operate O(N^2).
2076 */
2077static void
2078vlruvp(struct vnode *vp)
2079{
2080#if 0
2081	struct mount *mp;
2082
2083	if ((mp = vp->v_mount) != NULL) {
2084		mtx_lock(&mntvnode_mtx);
2085		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2086		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2087		mtx_unlock(&mntvnode_mtx);
2088	}
2089#endif
2090}
2091
2092/*
2093 * Disassociate the underlying filesystem from a vnode.
2094 */
2095static void
2096vclean(vp, flags, td)
2097	struct vnode *vp;
2098	int flags;
2099	struct thread *td;
2100{
2101	int active;
2102
2103	/*
2104	 * Check to see if the vnode is in use. If so we have to reference it
2105	 * before we clean it out so that its count cannot fall to zero and
2106	 * generate a race against ourselves to recycle it.
2107	 */
2108	if ((active = vp->v_usecount))
2109		vp->v_usecount++;
2110
2111	/*
2112	 * Prevent the vnode from being recycled or brought into use while we
2113	 * clean it out.
2114	 */
2115	if (vp->v_flag & VXLOCK)
2116		panic("vclean: deadlock");
2117	vp->v_flag |= VXLOCK;
2118	vp->v_vxproc = curthread;
2119	/*
2120	 * Even if the count is zero, the VOP_INACTIVE routine may still
2121	 * have the object locked while it cleans it out. The VOP_LOCK
2122	 * ensures that the VOP_INACTIVE routine is done with its work.
2123	 * For active vnodes, it ensures that no other activity can
2124	 * occur while the underlying object is being cleaned out.
2125	 */
2126	VOP_LOCK(vp, LK_DRAIN | LK_INTERLOCK, td);
2127
2128	/*
2129	 * Clean out any buffers associated with the vnode.
2130	 * If the flush fails, just toss the buffers.
2131	 */
2132	if (flags & DOCLOSE) {
2133		if (TAILQ_FIRST(&vp->v_dirtyblkhd) != NULL)
2134			(void) vn_write_suspend_wait(vp, NULL, V_WAIT);
2135		if (vinvalbuf(vp, V_SAVE, NOCRED, td, 0, 0) != 0)
2136			vinvalbuf(vp, 0, NOCRED, td, 0, 0);
2137	}
2138
2139	VOP_DESTROYVOBJECT(vp);
2140
2141	/*
2142	 * If purging an active vnode, it must be closed and
2143	 * deactivated before being reclaimed. Note that the
2144	 * VOP_INACTIVE will unlock the vnode.
2145	 */
2146	if (active) {
2147		if (flags & DOCLOSE)
2148			VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2149		VOP_INACTIVE(vp, td);
2150	} else {
2151		/*
2152		 * Any other processes trying to obtain this lock must first
2153		 * wait for VXLOCK to clear, then call the new lock operation.
2154		 */
2155		VOP_UNLOCK(vp, 0, td);
2156	}
2157	/*
2158	 * Reclaim the vnode.
2159	 */
2160	if (VOP_RECLAIM(vp, td))
2161		panic("vclean: cannot reclaim");
2162
2163	if (active) {
2164		/*
2165		 * Inline copy of vrele() since VOP_INACTIVE
2166		 * has already been called.
2167		 */
2168		mtx_lock(&vp->v_interlock);
2169		if (--vp->v_usecount <= 0) {
2170#ifdef DIAGNOSTIC
2171			if (vp->v_usecount < 0 || vp->v_writecount != 0) {
2172				vprint("vclean: bad ref count", vp);
2173				panic("vclean: ref cnt");
2174			}
2175#endif
2176			vfree(vp);
2177		}
2178		mtx_unlock(&vp->v_interlock);
2179	}
2180
2181	cache_purge(vp);
2182	vp->v_vnlock = NULL;
2183	lockdestroy(&vp->v_lock);
2184
2185	if (VSHOULDFREE(vp))
2186		vfree(vp);
2187
2188	/*
2189	 * Done with purge, notify sleepers of the grim news.
2190	 */
2191	vp->v_op = dead_vnodeop_p;
2192	if (vp->v_pollinfo != NULL)
2193		vn_pollgone(vp);
2194	vp->v_tag = VT_NON;
2195	vp->v_flag &= ~VXLOCK;
2196	vp->v_vxproc = NULL;
2197	if (vp->v_flag & VXWANT) {
2198		vp->v_flag &= ~VXWANT;
2199		wakeup(vp);
2200	}
2201}
2202
2203/*
2204 * Eliminate all activity associated with the requested vnode
2205 * and with all vnodes aliased to the requested vnode.
2206 */
2207int
2208vop_revoke(ap)
2209	struct vop_revoke_args /* {
2210		struct vnode *a_vp;
2211		int a_flags;
2212	} */ *ap;
2213{
2214	struct vnode *vp, *vq;
2215	dev_t dev;
2216
2217	KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
2218
2219	vp = ap->a_vp;
2220	/*
2221	 * If a vgone (or vclean) is already in progress,
2222	 * wait until it is done and return.
2223	 */
2224	if (vp->v_flag & VXLOCK) {
2225		vp->v_flag |= VXWANT;
2226		msleep(vp, &vp->v_interlock, PINOD | PDROP,
2227		    "vop_revokeall", 0);
2228		return (0);
2229	}
2230	dev = vp->v_rdev;
2231	for (;;) {
2232		mtx_lock(&spechash_mtx);
2233		vq = SLIST_FIRST(&dev->si_hlist);
2234		mtx_unlock(&spechash_mtx);
2235		if (!vq)
2236			break;
2237		vgone(vq);
2238	}
2239	return (0);
2240}
2241
2242/*
2243 * Recycle an unused vnode to the front of the free list.
2244 * Release the passed interlock if the vnode will be recycled.
2245 */
2246int
2247vrecycle(vp, inter_lkp, td)
2248	struct vnode *vp;
2249	struct mtx *inter_lkp;
2250	struct thread *td;
2251{
2252
2253	mtx_lock(&vp->v_interlock);
2254	if (vp->v_usecount == 0) {
2255		if (inter_lkp) {
2256			mtx_unlock(inter_lkp);
2257		}
2258		vgonel(vp, td);
2259		return (1);
2260	}
2261	mtx_unlock(&vp->v_interlock);
2262	return (0);
2263}
2264
2265/*
2266 * Eliminate all activity associated with a vnode
2267 * in preparation for reuse.
2268 */
2269void
2270vgone(vp)
2271	register struct vnode *vp;
2272{
2273	struct thread *td = curthread;	/* XXX */
2274
2275	mtx_lock(&vp->v_interlock);
2276	vgonel(vp, td);
2277}
2278
2279/*
2280 * vgone, with the vp interlock held.
2281 */
2282void
2283vgonel(vp, td)
2284	struct vnode *vp;
2285	struct thread *td;
2286{
2287	int s;
2288
2289	/*
2290	 * If a vgone (or vclean) is already in progress,
2291	 * wait until it is done and return.
2292	 */
2293	if (vp->v_flag & VXLOCK) {
2294		vp->v_flag |= VXWANT;
2295		msleep(vp, &vp->v_interlock, PINOD | PDROP, "vgone", 0);
2296		return;
2297	}
2298
2299	/*
2300	 * Clean out the filesystem specific data.
2301	 */
2302	vclean(vp, DOCLOSE, td);
2303	mtx_lock(&vp->v_interlock);
2304
2305	/*
2306	 * Delete from old mount point vnode list, if on one.
2307	 */
2308	if (vp->v_mount != NULL)
2309		insmntque(vp, (struct mount *)0);
2310	/*
2311	 * If special device, remove it from special device alias list
2312	 * if it is on one.
2313	 */
2314	if (vp->v_type == VCHR && vp->v_rdev != NULL && vp->v_rdev != NODEV) {
2315		mtx_lock(&spechash_mtx);
2316		SLIST_REMOVE(&vp->v_rdev->si_hlist, vp, vnode, v_specnext);
2317		freedev(vp->v_rdev);
2318		mtx_unlock(&spechash_mtx);
2319		vp->v_rdev = NULL;
2320	}
2321
2322	/*
2323	 * If it is on the freelist and not already at the head,
2324	 * move it to the head of the list. The test of the
2325	 * VDOOMED flag and the reference count of zero is because
2326	 * it will be removed from the free list by getnewvnode,
2327	 * but will not have its reference count incremented until
2328	 * after calling vgone. If the reference count were
2329	 * incremented first, vgone would (incorrectly) try to
2330	 * close the previous instance of the underlying object.
2331	 */
2332	if (vp->v_usecount == 0 && !(vp->v_flag & VDOOMED)) {
2333		s = splbio();
2334		mtx_lock(&vnode_free_list_mtx);
2335		if (vp->v_flag & VFREE)
2336			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2337		else
2338			freevnodes++;
2339		vp->v_flag |= VFREE;
2340		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2341		mtx_unlock(&vnode_free_list_mtx);
2342		splx(s);
2343	}
2344
2345	vp->v_type = VBAD;
2346	mtx_unlock(&vp->v_interlock);
2347}
2348
2349/*
2350 * Lookup a vnode by device number.
2351 */
2352int
2353vfinddev(dev, type, vpp)
2354	dev_t dev;
2355	enum vtype type;
2356	struct vnode **vpp;
2357{
2358	struct vnode *vp;
2359
2360	mtx_lock(&spechash_mtx);
2361	SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
2362		if (type == vp->v_type) {
2363			*vpp = vp;
2364			mtx_unlock(&spechash_mtx);
2365			return (1);
2366		}
2367	}
2368	mtx_unlock(&spechash_mtx);
2369	return (0);
2370}
2371
2372/*
2373 * Calculate the total number of references to a special device.
2374 */
2375int
2376vcount(vp)
2377	struct vnode *vp;
2378{
2379	struct vnode *vq;
2380	int count;
2381
2382	count = 0;
2383	mtx_lock(&spechash_mtx);
2384	SLIST_FOREACH(vq, &vp->v_rdev->si_hlist, v_specnext)
2385		count += vq->v_usecount;
2386	mtx_unlock(&spechash_mtx);
2387	return (count);
2388}
2389
2390/*
2391 * Same as above, but using the dev_t as argument
2392 */
2393int
2394count_dev(dev)
2395	dev_t dev;
2396{
2397	struct vnode *vp;
2398
2399	vp = SLIST_FIRST(&dev->si_hlist);
2400	if (vp == NULL)
2401		return (0);
2402	return(vcount(vp));
2403}
2404
2405/*
2406 * Print out a description of a vnode.
2407 */
2408static char *typename[] =
2409{"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
2410
2411void
2412vprint(label, vp)
2413	char *label;
2414	struct vnode *vp;
2415{
2416	char buf[96];
2417
2418	if (label != NULL)
2419		printf("%s: %p: ", label, (void *)vp);
2420	else
2421		printf("%p: ", (void *)vp);
2422	printf("type %s, usecount %d, writecount %d, refcount %d,",
2423	    typename[vp->v_type], vp->v_usecount, vp->v_writecount,
2424	    vp->v_holdcnt);
2425	buf[0] = '\0';
2426	if (vp->v_flag & VROOT)
2427		strcat(buf, "|VROOT");
2428	if (vp->v_flag & VTEXT)
2429		strcat(buf, "|VTEXT");
2430	if (vp->v_flag & VSYSTEM)
2431		strcat(buf, "|VSYSTEM");
2432	if (vp->v_flag & VXLOCK)
2433		strcat(buf, "|VXLOCK");
2434	if (vp->v_flag & VXWANT)
2435		strcat(buf, "|VXWANT");
2436	if (vp->v_flag & VBWAIT)
2437		strcat(buf, "|VBWAIT");
2438	if (vp->v_flag & VDOOMED)
2439		strcat(buf, "|VDOOMED");
2440	if (vp->v_flag & VFREE)
2441		strcat(buf, "|VFREE");
2442	if (vp->v_flag & VOBJBUF)
2443		strcat(buf, "|VOBJBUF");
2444	if (buf[0] != '\0')
2445		printf(" flags (%s)", &buf[1]);
2446	if (vp->v_data == NULL) {
2447		printf("\n");
2448	} else {
2449		printf("\n\t");
2450		VOP_PRINT(vp);
2451	}
2452}
2453
2454#ifdef DDB
2455#include <ddb/ddb.h>
2456/*
2457 * List all of the locked vnodes in the system.
2458 * Called when debugging the kernel.
2459 */
2460DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2461{
2462	struct thread *td = curthread;	/* XXX */
2463	struct mount *mp, *nmp;
2464	struct vnode *vp;
2465
2466	printf("Locked vnodes\n");
2467	mtx_lock(&mountlist_mtx);
2468	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2469		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td)) {
2470			nmp = TAILQ_NEXT(mp, mnt_list);
2471			continue;
2472		}
2473		mtx_lock(&mntvnode_mtx);
2474		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2475			if (VOP_ISLOCKED(vp, NULL))
2476				vprint((char *)0, vp);
2477		}
2478		mtx_unlock(&mntvnode_mtx);
2479		mtx_lock(&mountlist_mtx);
2480		nmp = TAILQ_NEXT(mp, mnt_list);
2481		vfs_unbusy(mp, td);
2482	}
2483	mtx_unlock(&mountlist_mtx);
2484}
2485#endif
2486
2487/*
2488 * Top level filesystem related information gathering.
2489 */
2490static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
2491
2492static int
2493vfs_sysctl(SYSCTL_HANDLER_ARGS)
2494{
2495	int *name = (int *)arg1 - 1;	/* XXX */
2496	u_int namelen = arg2 + 1;	/* XXX */
2497	struct vfsconf *vfsp;
2498
2499#if 1 || defined(COMPAT_PRELITE2)
2500	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2501	if (namelen == 1)
2502		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2503#endif
2504
2505	/* XXX the below code does not compile; vfs_sysctl does not exist. */
2506#ifdef notyet
2507	/* all sysctl names at this level are at least name and field */
2508	if (namelen < 2)
2509		return (ENOTDIR);		/* overloaded */
2510	if (name[0] != VFS_GENERIC) {
2511		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2512			if (vfsp->vfc_typenum == name[0])
2513				break;
2514		if (vfsp == NULL)
2515			return (EOPNOTSUPP);
2516		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
2517		    oldp, oldlenp, newp, newlen, td));
2518	}
2519#endif
2520	switch (name[1]) {
2521	case VFS_MAXTYPENUM:
2522		if (namelen != 2)
2523			return (ENOTDIR);
2524		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2525	case VFS_CONF:
2526		if (namelen != 3)
2527			return (ENOTDIR);	/* overloaded */
2528		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2529			if (vfsp->vfc_typenum == name[2])
2530				break;
2531		if (vfsp == NULL)
2532			return (EOPNOTSUPP);
2533		return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
2534	}
2535	return (EOPNOTSUPP);
2536}
2537
2538SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
2539	"Generic filesystem");
2540
2541#if 1 || defined(COMPAT_PRELITE2)
2542
2543static int
2544sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2545{
2546	int error;
2547	struct vfsconf *vfsp;
2548	struct ovfsconf ovfs;
2549
2550	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
2551		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2552		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2553		ovfs.vfc_index = vfsp->vfc_typenum;
2554		ovfs.vfc_refcount = vfsp->vfc_refcount;
2555		ovfs.vfc_flags = vfsp->vfc_flags;
2556		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2557		if (error)
2558			return error;
2559	}
2560	return 0;
2561}
2562
2563#endif /* 1 || COMPAT_PRELITE2 */
2564
2565#if COMPILING_LINT
2566#define KINFO_VNODESLOP	10
2567/*
2568 * Dump vnode list (via sysctl).
2569 * Copyout address of vnode followed by vnode.
2570 */
2571/* ARGSUSED */
2572static int
2573sysctl_vnode(SYSCTL_HANDLER_ARGS)
2574{
2575	struct thread *td = curthread;	/* XXX */
2576	struct mount *mp, *nmp;
2577	struct vnode *nvp, *vp;
2578	int error;
2579
2580#define VPTRSZ	sizeof (struct vnode *)
2581#define VNODESZ	sizeof (struct vnode)
2582
2583	req->lock = 0;
2584	if (!req->oldptr) /* Make an estimate */
2585		return (SYSCTL_OUT(req, 0,
2586			(numvnodes + KINFO_VNODESLOP) * (VPTRSZ + VNODESZ)));
2587
2588	mtx_lock(&mountlist_mtx);
2589	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2590		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td)) {
2591			nmp = TAILQ_NEXT(mp, mnt_list);
2592			continue;
2593		}
2594		mtx_lock(&mntvnode_mtx);
2595again:
2596		for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
2597		     vp != NULL;
2598		     vp = nvp) {
2599			/*
2600			 * Check that the vp is still associated with
2601			 * this filesystem.  RACE: could have been
2602			 * recycled onto the same filesystem.
2603			 */
2604			if (vp->v_mount != mp)
2605				goto again;
2606			nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2607			mtx_unlock(&mntvnode_mtx);
2608			if ((error = SYSCTL_OUT(req, &vp, VPTRSZ)) ||
2609			    (error = SYSCTL_OUT(req, vp, VNODESZ)))
2610				return (error);
2611			mtx_lock(&mntvnode_mtx);
2612		}
2613		mtx_unlock(&mntvnode_mtx);
2614		mtx_lock(&mountlist_mtx);
2615		nmp = TAILQ_NEXT(mp, mnt_list);
2616		vfs_unbusy(mp, td);
2617	}
2618	mtx_unlock(&mountlist_mtx);
2619
2620	return (0);
2621}
2622
2623/*
2624 * XXX
2625 * Exporting the vnode list on large systems causes them to crash.
2626 * Exporting the vnode list on medium systems causes sysctl to coredump.
2627 */
2628SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2629	0, 0, sysctl_vnode, "S,vnode", "");
2630#endif
2631
2632/*
2633 * Check to see if a filesystem is mounted on a block device.
2634 */
2635int
2636vfs_mountedon(vp)
2637	struct vnode *vp;
2638{
2639
2640	if (vp->v_rdev->si_mountpoint != NULL)
2641		return (EBUSY);
2642	return (0);
2643}
2644
2645/*
2646 * Unmount all filesystems. The list is traversed in reverse order
2647 * of mounting to avoid dependencies.
2648 */
2649void
2650vfs_unmountall()
2651{
2652	struct mount *mp;
2653	struct thread *td;
2654	int error;
2655
2656	if (curthread != NULL)
2657		td = curthread;
2658	else
2659		td = FIRST_THREAD_IN_PROC(initproc); /* XXX XXX proc0? */
2660	/*
2661	 * Since this only runs when rebooting, it is not interlocked.
2662	 */
2663	while(!TAILQ_EMPTY(&mountlist)) {
2664		mp = TAILQ_LAST(&mountlist, mntlist);
2665		error = dounmount(mp, MNT_FORCE, td);
2666		if (error) {
2667			TAILQ_REMOVE(&mountlist, mp, mnt_list);
2668			printf("unmount of %s failed (",
2669			    mp->mnt_stat.f_mntonname);
2670			if (error == EBUSY)
2671				printf("BUSY)\n");
2672			else
2673				printf("%d)\n", error);
2674		} else {
2675			/* The unmount has removed mp from the mountlist */
2676		}
2677	}
2678}
2679
2680/*
2681 * perform msync on all vnodes under a mount point
2682 * the mount point must be locked.
2683 */
2684void
2685vfs_msync(struct mount *mp, int flags)
2686{
2687	struct vnode *vp, *nvp;
2688	struct vm_object *obj;
2689	int tries;
2690
2691	GIANT_REQUIRED;
2692
2693	tries = 5;
2694	mtx_lock(&mntvnode_mtx);
2695loop:
2696	for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp != NULL; vp = nvp) {
2697		if (vp->v_mount != mp) {
2698			if (--tries > 0)
2699				goto loop;
2700			break;
2701		}
2702		nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2703
2704		if (vp->v_flag & VXLOCK)	/* XXX: what if MNT_WAIT? */
2705			continue;
2706
2707		if (vp->v_flag & VNOSYNC)	/* unlinked, skip it */
2708			continue;
2709
2710		if ((vp->v_flag & VOBJDIRTY) &&
2711		    (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
2712			mtx_unlock(&mntvnode_mtx);
2713			if (!vget(vp,
2714			    LK_EXCLUSIVE | LK_RETRY | LK_NOOBJ, curthread)) {
2715				if (VOP_GETVOBJECT(vp, &obj) == 0) {
2716					vm_object_page_clean(obj, 0, 0,
2717					    flags == MNT_WAIT ?
2718					    OBJPC_SYNC : OBJPC_NOSYNC);
2719				}
2720				vput(vp);
2721			}
2722			mtx_lock(&mntvnode_mtx);
2723			if (TAILQ_NEXT(vp, v_nmntvnodes) != nvp) {
2724				if (--tries > 0)
2725					goto loop;
2726				break;
2727			}
2728		}
2729	}
2730	mtx_unlock(&mntvnode_mtx);
2731}
2732
2733/*
2734 * Create the VM object needed for VMIO and mmap support.  This
2735 * is done for all VREG files in the system.  Some filesystems might
2736 * afford the additional metadata buffering capability of the
2737 * VMIO code by making the device node be VMIO mode also.
2738 *
2739 * vp must be locked when vfs_object_create is called.
2740 */
2741int
2742vfs_object_create(vp, td, cred)
2743	struct vnode *vp;
2744	struct thread *td;
2745	struct ucred *cred;
2746{
2747	GIANT_REQUIRED;
2748	return (VOP_CREATEVOBJECT(vp, cred, td));
2749}
2750
2751/*
2752 * Mark a vnode as free, putting it up for recycling.
2753 */
2754void
2755vfree(vp)
2756	struct vnode *vp;
2757{
2758	int s;
2759
2760	s = splbio();
2761	mtx_lock(&vnode_free_list_mtx);
2762	KASSERT((vp->v_flag & VFREE) == 0, ("vnode already free"));
2763	if (vp->v_flag & VAGE) {
2764		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2765	} else {
2766		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2767	}
2768	freevnodes++;
2769	mtx_unlock(&vnode_free_list_mtx);
2770	vp->v_flag &= ~VAGE;
2771	vp->v_flag |= VFREE;
2772	splx(s);
2773}
2774
2775/*
2776 * Opposite of vfree() - mark a vnode as in use.
2777 */
2778void
2779vbusy(vp)
2780	struct vnode *vp;
2781{
2782	int s;
2783
2784	s = splbio();
2785	mtx_lock(&vnode_free_list_mtx);
2786	KASSERT((vp->v_flag & VFREE) != 0, ("vnode not free"));
2787	TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2788	freevnodes--;
2789	mtx_unlock(&vnode_free_list_mtx);
2790	vp->v_flag &= ~(VFREE|VAGE);
2791	splx(s);
2792}
2793
2794/*
2795 * Record a process's interest in events which might happen to
2796 * a vnode.  Because poll uses the historic select-style interface
2797 * internally, this routine serves as both the ``check for any
2798 * pending events'' and the ``record my interest in future events''
2799 * functions.  (These are done together, while the lock is held,
2800 * to avoid race conditions.)
2801 */
2802int
2803vn_pollrecord(vp, td, events)
2804	struct vnode *vp;
2805	struct thread *td;
2806	short events;
2807{
2808
2809	if (vp->v_pollinfo == NULL)
2810		v_addpollinfo(vp);
2811	mtx_lock(&vp->v_pollinfo->vpi_lock);
2812	if (vp->v_pollinfo->vpi_revents & events) {
2813		/*
2814		 * This leaves events we are not interested
2815		 * in available for the other process which
2816		 * which presumably had requested them
2817		 * (otherwise they would never have been
2818		 * recorded).
2819		 */
2820		events &= vp->v_pollinfo->vpi_revents;
2821		vp->v_pollinfo->vpi_revents &= ~events;
2822
2823		mtx_unlock(&vp->v_pollinfo->vpi_lock);
2824		return events;
2825	}
2826	vp->v_pollinfo->vpi_events |= events;
2827	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
2828	mtx_unlock(&vp->v_pollinfo->vpi_lock);
2829	return 0;
2830}
2831
2832/*
2833 * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2834 * it is possible for us to miss an event due to race conditions, but
2835 * that condition is expected to be rare, so for the moment it is the
2836 * preferred interface.
2837 */
2838void
2839vn_pollevent(vp, events)
2840	struct vnode *vp;
2841	short events;
2842{
2843
2844	if (vp->v_pollinfo == NULL)
2845		v_addpollinfo(vp);
2846	mtx_lock(&vp->v_pollinfo->vpi_lock);
2847	if (vp->v_pollinfo->vpi_events & events) {
2848		/*
2849		 * We clear vpi_events so that we don't
2850		 * call selwakeup() twice if two events are
2851		 * posted before the polling process(es) is
2852		 * awakened.  This also ensures that we take at
2853		 * most one selwakeup() if the polling process
2854		 * is no longer interested.  However, it does
2855		 * mean that only one event can be noticed at
2856		 * a time.  (Perhaps we should only clear those
2857		 * event bits which we note?) XXX
2858		 */
2859		vp->v_pollinfo->vpi_events = 0;	/* &= ~events ??? */
2860		vp->v_pollinfo->vpi_revents |= events;
2861		selwakeup(&vp->v_pollinfo->vpi_selinfo);
2862	}
2863	mtx_unlock(&vp->v_pollinfo->vpi_lock);
2864}
2865
2866/*
2867 * Wake up anyone polling on vp because it is being revoked.
2868 * This depends on dead_poll() returning POLLHUP for correct
2869 * behavior.
2870 */
2871void
2872vn_pollgone(vp)
2873	struct vnode *vp;
2874{
2875
2876	mtx_lock(&vp->v_pollinfo->vpi_lock);
2877	VN_KNOTE(vp, NOTE_REVOKE);
2878	if (vp->v_pollinfo->vpi_events) {
2879		vp->v_pollinfo->vpi_events = 0;
2880		selwakeup(&vp->v_pollinfo->vpi_selinfo);
2881	}
2882	mtx_unlock(&vp->v_pollinfo->vpi_lock);
2883}
2884
2885
2886
2887/*
2888 * Routine to create and manage a filesystem syncer vnode.
2889 */
2890#define sync_close ((int (*)(struct  vop_close_args *))nullop)
2891static int	sync_fsync(struct  vop_fsync_args *);
2892static int	sync_inactive(struct  vop_inactive_args *);
2893static int	sync_reclaim(struct  vop_reclaim_args *);
2894#define sync_lock ((int (*)(struct  vop_lock_args *))vop_nolock)
2895#define sync_unlock ((int (*)(struct  vop_unlock_args *))vop_nounlock)
2896static int	sync_print(struct vop_print_args *);
2897#define sync_islocked ((int(*)(struct vop_islocked_args *))vop_noislocked)
2898
2899static vop_t **sync_vnodeop_p;
2900static struct vnodeopv_entry_desc sync_vnodeop_entries[] = {
2901	{ &vop_default_desc,	(vop_t *) vop_eopnotsupp },
2902	{ &vop_close_desc,	(vop_t *) sync_close },		/* close */
2903	{ &vop_fsync_desc,	(vop_t *) sync_fsync },		/* fsync */
2904	{ &vop_inactive_desc,	(vop_t *) sync_inactive },	/* inactive */
2905	{ &vop_reclaim_desc,	(vop_t *) sync_reclaim },	/* reclaim */
2906	{ &vop_lock_desc,	(vop_t *) sync_lock },		/* lock */
2907	{ &vop_unlock_desc,	(vop_t *) sync_unlock },	/* unlock */
2908	{ &vop_print_desc,	(vop_t *) sync_print },		/* print */
2909	{ &vop_islocked_desc,	(vop_t *) sync_islocked },	/* islocked */
2910	{ NULL, NULL }
2911};
2912static struct vnodeopv_desc sync_vnodeop_opv_desc =
2913	{ &sync_vnodeop_p, sync_vnodeop_entries };
2914
2915VNODEOP_SET(sync_vnodeop_opv_desc);
2916
2917/*
2918 * Create a new filesystem syncer vnode for the specified mount point.
2919 */
2920int
2921vfs_allocate_syncvnode(mp)
2922	struct mount *mp;
2923{
2924	struct vnode *vp;
2925	static long start, incr, next;
2926	int error;
2927
2928	/* Allocate a new vnode */
2929	if ((error = getnewvnode(VT_VFS, mp, sync_vnodeop_p, &vp)) != 0) {
2930		mp->mnt_syncer = NULL;
2931		return (error);
2932	}
2933	vp->v_type = VNON;
2934	/*
2935	 * Place the vnode onto the syncer worklist. We attempt to
2936	 * scatter them about on the list so that they will go off
2937	 * at evenly distributed times even if all the filesystems
2938	 * are mounted at once.
2939	 */
2940	next += incr;
2941	if (next == 0 || next > syncer_maxdelay) {
2942		start /= 2;
2943		incr /= 2;
2944		if (start == 0) {
2945			start = syncer_maxdelay / 2;
2946			incr = syncer_maxdelay;
2947		}
2948		next = start;
2949	}
2950	vn_syncer_add_to_worklist(vp, syncdelay > 0 ? next % syncdelay : 0);
2951	mp->mnt_syncer = vp;
2952	return (0);
2953}
2954
2955/*
2956 * Do a lazy sync of the filesystem.
2957 */
2958static int
2959sync_fsync(ap)
2960	struct vop_fsync_args /* {
2961		struct vnode *a_vp;
2962		struct ucred *a_cred;
2963		int a_waitfor;
2964		struct thread *a_td;
2965	} */ *ap;
2966{
2967	struct vnode *syncvp = ap->a_vp;
2968	struct mount *mp = syncvp->v_mount;
2969	struct thread *td = ap->a_td;
2970	int asyncflag;
2971
2972	/*
2973	 * We only need to do something if this is a lazy evaluation.
2974	 */
2975	if (ap->a_waitfor != MNT_LAZY)
2976		return (0);
2977
2978	/*
2979	 * Move ourselves to the back of the sync list.
2980	 */
2981	vn_syncer_add_to_worklist(syncvp, syncdelay);
2982
2983	/*
2984	 * Walk the list of vnodes pushing all that are dirty and
2985	 * not already on the sync list.
2986	 */
2987	mtx_lock(&mountlist_mtx);
2988	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_mtx, td) != 0) {
2989		mtx_unlock(&mountlist_mtx);
2990		return (0);
2991	}
2992	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
2993		vfs_unbusy(mp, td);
2994		return (0);
2995	}
2996	asyncflag = mp->mnt_flag & MNT_ASYNC;
2997	mp->mnt_flag &= ~MNT_ASYNC;
2998	vfs_msync(mp, MNT_NOWAIT);
2999	VFS_SYNC(mp, MNT_LAZY, ap->a_cred, td);
3000	if (asyncflag)
3001		mp->mnt_flag |= MNT_ASYNC;
3002	vn_finished_write(mp);
3003	vfs_unbusy(mp, td);
3004	return (0);
3005}
3006
3007/*
3008 * The syncer vnode is no referenced.
3009 */
3010static int
3011sync_inactive(ap)
3012	struct vop_inactive_args /* {
3013		struct vnode *a_vp;
3014		struct thread *a_td;
3015	} */ *ap;
3016{
3017
3018	vgone(ap->a_vp);
3019	return (0);
3020}
3021
3022/*
3023 * The syncer vnode is no longer needed and is being decommissioned.
3024 *
3025 * Modifications to the worklist must be protected at splbio().
3026 */
3027static int
3028sync_reclaim(ap)
3029	struct vop_reclaim_args /* {
3030		struct vnode *a_vp;
3031	} */ *ap;
3032{
3033	struct vnode *vp = ap->a_vp;
3034	int s;
3035
3036	s = splbio();
3037	vp->v_mount->mnt_syncer = NULL;
3038	if (vp->v_flag & VONWORKLST) {
3039		LIST_REMOVE(vp, v_synclist);
3040		vp->v_flag &= ~VONWORKLST;
3041	}
3042	splx(s);
3043
3044	return (0);
3045}
3046
3047/*
3048 * Print out a syncer vnode.
3049 */
3050static int
3051sync_print(ap)
3052	struct vop_print_args /* {
3053		struct vnode *a_vp;
3054	} */ *ap;
3055{
3056	struct vnode *vp = ap->a_vp;
3057
3058	printf("syncer vnode");
3059	if (vp->v_vnlock != NULL)
3060		lockmgr_printinfo(vp->v_vnlock);
3061	printf("\n");
3062	return (0);
3063}
3064
3065/*
3066 * extract the dev_t from a VCHR
3067 */
3068dev_t
3069vn_todev(vp)
3070	struct vnode *vp;
3071{
3072	if (vp->v_type != VCHR)
3073		return (NODEV);
3074	return (vp->v_rdev);
3075}
3076
3077/*
3078 * Check if vnode represents a disk device
3079 */
3080int
3081vn_isdisk(vp, errp)
3082	struct vnode *vp;
3083	int *errp;
3084{
3085	struct cdevsw *cdevsw;
3086
3087	if (vp->v_type != VCHR) {
3088		if (errp != NULL)
3089			*errp = ENOTBLK;
3090		return (0);
3091	}
3092	if (vp->v_rdev == NULL) {
3093		if (errp != NULL)
3094			*errp = ENXIO;
3095		return (0);
3096	}
3097	cdevsw = devsw(vp->v_rdev);
3098	if (cdevsw == NULL) {
3099		if (errp != NULL)
3100			*errp = ENXIO;
3101		return (0);
3102	}
3103	if (!(cdevsw->d_flags & D_DISK)) {
3104		if (errp != NULL)
3105			*errp = ENOTBLK;
3106		return (0);
3107	}
3108	if (errp != NULL)
3109		*errp = 0;
3110	return (1);
3111}
3112
3113/*
3114 * Free data allocated by namei(); see namei(9) for details.
3115 */
3116void
3117NDFREE(ndp, flags)
3118     struct nameidata *ndp;
3119     const uint flags;
3120{
3121	if (!(flags & NDF_NO_FREE_PNBUF) &&
3122	    (ndp->ni_cnd.cn_flags & HASBUF)) {
3123		uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
3124		ndp->ni_cnd.cn_flags &= ~HASBUF;
3125	}
3126	if (!(flags & NDF_NO_DVP_UNLOCK) &&
3127	    (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
3128	    ndp->ni_dvp != ndp->ni_vp)
3129		VOP_UNLOCK(ndp->ni_dvp, 0, ndp->ni_cnd.cn_thread);
3130	if (!(flags & NDF_NO_DVP_RELE) &&
3131	    (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
3132		vrele(ndp->ni_dvp);
3133		ndp->ni_dvp = NULL;
3134	}
3135	if (!(flags & NDF_NO_VP_UNLOCK) &&
3136	    (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
3137		VOP_UNLOCK(ndp->ni_vp, 0, ndp->ni_cnd.cn_thread);
3138	if (!(flags & NDF_NO_VP_RELE) &&
3139	    ndp->ni_vp) {
3140		vrele(ndp->ni_vp);
3141		ndp->ni_vp = NULL;
3142	}
3143	if (!(flags & NDF_NO_STARTDIR_RELE) &&
3144	    (ndp->ni_cnd.cn_flags & SAVESTART)) {
3145		vrele(ndp->ni_startdir);
3146		ndp->ni_startdir = NULL;
3147	}
3148}
3149
3150/*
3151 * Common filesystem object access control check routine.  Accepts a
3152 * vnode's type, "mode", uid and gid, requested access mode, credentials,
3153 * and optional call-by-reference privused argument allowing vaccess()
3154 * to indicate to the caller whether privilege was used to satisfy the
3155 * request.  Returns 0 on success, or an errno on failure.
3156 */
3157int
3158vaccess(type, file_mode, file_uid, file_gid, acc_mode, cred, privused)
3159	enum vtype type;
3160	mode_t file_mode;
3161	uid_t file_uid;
3162	gid_t file_gid;
3163	mode_t acc_mode;
3164	struct ucred *cred;
3165	int *privused;
3166{
3167	mode_t dac_granted;
3168#ifdef CAPABILITIES
3169	mode_t cap_granted;
3170#endif
3171
3172	/*
3173	 * Look for a normal, non-privileged way to access the file/directory
3174	 * as requested.  If it exists, go with that.
3175	 */
3176
3177	if (privused != NULL)
3178		*privused = 0;
3179
3180	dac_granted = 0;
3181
3182	/* Check the owner. */
3183	if (cred->cr_uid == file_uid) {
3184		dac_granted |= VADMIN;
3185		if (file_mode & S_IXUSR)
3186			dac_granted |= VEXEC;
3187		if (file_mode & S_IRUSR)
3188			dac_granted |= VREAD;
3189		if (file_mode & S_IWUSR)
3190			dac_granted |= VWRITE;
3191
3192		if ((acc_mode & dac_granted) == acc_mode)
3193			return (0);
3194
3195		goto privcheck;
3196	}
3197
3198	/* Otherwise, check the groups (first match) */
3199	if (groupmember(file_gid, cred)) {
3200		if (file_mode & S_IXGRP)
3201			dac_granted |= VEXEC;
3202		if (file_mode & S_IRGRP)
3203			dac_granted |= VREAD;
3204		if (file_mode & S_IWGRP)
3205			dac_granted |= VWRITE;
3206
3207		if ((acc_mode & dac_granted) == acc_mode)
3208			return (0);
3209
3210		goto privcheck;
3211	}
3212
3213	/* Otherwise, check everyone else. */
3214	if (file_mode & S_IXOTH)
3215		dac_granted |= VEXEC;
3216	if (file_mode & S_IROTH)
3217		dac_granted |= VREAD;
3218	if (file_mode & S_IWOTH)
3219		dac_granted |= VWRITE;
3220	if ((acc_mode & dac_granted) == acc_mode)
3221		return (0);
3222
3223privcheck:
3224	if (!suser_cred(cred, PRISON_ROOT)) {
3225		/* XXX audit: privilege used */
3226		if (privused != NULL)
3227			*privused = 1;
3228		return (0);
3229	}
3230
3231#ifdef CAPABILITIES
3232	/*
3233	 * Build a capability mask to determine if the set of capabilities
3234	 * satisfies the requirements when combined with the granted mask
3235	 * from above.
3236	 * For each capability, if the capability is required, bitwise
3237	 * or the request type onto the cap_granted mask.
3238	 */
3239	cap_granted = 0;
3240
3241	if (type == VDIR) {
3242		/*
3243		 * For directories, use CAP_DAC_READ_SEARCH to satisfy
3244		 * VEXEC requests, instead of CAP_DAC_EXECUTE.
3245		 */
3246		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3247		    !cap_check(cred, NULL, CAP_DAC_READ_SEARCH, PRISON_ROOT))
3248			cap_granted |= VEXEC;
3249	} else {
3250		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3251		    !cap_check(cred, NULL, CAP_DAC_EXECUTE, PRISON_ROOT))
3252			cap_granted |= VEXEC;
3253	}
3254
3255	if ((acc_mode & VREAD) && ((dac_granted & VREAD) == 0) &&
3256	    !cap_check(cred, NULL, CAP_DAC_READ_SEARCH, PRISON_ROOT))
3257		cap_granted |= VREAD;
3258
3259	if ((acc_mode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3260	    !cap_check(cred, NULL, CAP_DAC_WRITE, PRISON_ROOT))
3261		cap_granted |= VWRITE;
3262
3263	if ((acc_mode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3264	    !cap_check(cred, NULL, CAP_FOWNER, PRISON_ROOT))
3265		cap_granted |= VADMIN;
3266
3267	if ((acc_mode & (cap_granted | dac_granted)) == acc_mode) {
3268		/* XXX audit: privilege used */
3269		if (privused != NULL)
3270			*privused = 1;
3271		return (0);
3272	}
3273#endif
3274
3275	return ((acc_mode & VADMIN) ? EPERM : EACCES);
3276}
3277