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