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