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