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