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