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