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