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