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