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