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