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