xref: /freebsd/sys/kern/vfs_export.c (revision 4cf49a43559ed9fdad601bdcccd2c55963008675)
1 /*
2  * Copyright (c) 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * (c) UNIX System Laboratories, Inc.
5  * All or some portions of this file are derived from material licensed
6  * to the University of California by American Telephone and Telegraph
7  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
8  * the permission of UNIX System Laboratories, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. All advertising materials mentioning features or use of this software
19  *    must display the following acknowledgement:
20  *	This product includes software developed by the University of
21  *	California, Berkeley and its contributors.
22  * 4. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
39  * $FreeBSD$
40  */
41 
42 /*
43  * External virtual filesystem routines
44  */
45 #include "opt_ddb.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/fcntl.h>
50 #include <sys/kernel.h>
51 #include <sys/proc.h>
52 #include <sys/kthread.h>
53 #include <sys/malloc.h>
54 #include <sys/mount.h>
55 #include <sys/socket.h>
56 #include <sys/vnode.h>
57 #include <sys/stat.h>
58 #include <sys/buf.h>
59 #include <sys/domain.h>
60 #include <sys/dirent.h>
61 #include <sys/vmmeter.h>
62 #include <sys/conf.h>
63 
64 #include <machine/limits.h>
65 
66 #include <vm/vm.h>
67 #include <vm/vm_prot.h>
68 #include <vm/vm_object.h>
69 #include <vm/vm_extern.h>
70 #include <vm/pmap.h>
71 #include <vm/vm_map.h>
72 #include <vm/vm_page.h>
73 #include <vm/vm_pager.h>
74 #include <vm/vnode_pager.h>
75 #include <vm/vm_zone.h>
76 #include <sys/sysctl.h>
77 
78 static MALLOC_DEFINE(M_NETADDR, "Export Host", "Export host address structure");
79 
80 static void	insmntque __P((struct vnode *vp, struct mount *mp));
81 static void	vclean __P((struct vnode *vp, int flags, struct proc *p));
82 static void	vfree __P((struct vnode *));
83 static void	vgonel __P((struct vnode *vp, struct proc *p));
84 static unsigned long	numvnodes;
85 SYSCTL_INT(_debug, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
86 
87 enum vtype iftovt_tab[16] = {
88 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
89 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
90 };
91 int vttoif_tab[9] = {
92 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
93 	S_IFSOCK, S_IFIFO, S_IFMT,
94 };
95 
96 static TAILQ_HEAD(freelst, vnode) vnode_free_list;	/* vnode free list */
97 struct tobefreelist vnode_tobefree_list;	/* vnode free list */
98 
99 static u_long wantfreevnodes = 25;
100 SYSCTL_INT(_debug, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
101 static u_long freevnodes = 0;
102 SYSCTL_INT(_debug, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
103 
104 static int reassignbufcalls;
105 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
106 static int reassignbufloops;
107 SYSCTL_INT(_vfs, OID_AUTO, reassignbufloops, CTLFLAG_RW, &reassignbufloops, 0, "");
108 static int reassignbufsortgood;
109 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortgood, CTLFLAG_RW, &reassignbufsortgood, 0, "");
110 static int reassignbufsortbad;
111 SYSCTL_INT(_vfs, OID_AUTO, reassignbufsortbad, CTLFLAG_RW, &reassignbufsortbad, 0, "");
112 static int reassignbufmethod = 1;
113 SYSCTL_INT(_vfs, OID_AUTO, reassignbufmethod, CTLFLAG_RW, &reassignbufmethod, 0, "");
114 
115 #ifdef ENABLE_VFS_IOOPT
116 int vfs_ioopt = 0;
117 SYSCTL_INT(_vfs, OID_AUTO, ioopt, CTLFLAG_RW, &vfs_ioopt, 0, "");
118 #endif
119 
120 struct mntlist mountlist;	/* mounted filesystem list */
121 struct simplelock mountlist_slock;
122 struct simplelock mntvnode_slock;
123 int	nfs_mount_type = -1;
124 #ifndef NULL_SIMPLELOCKS
125 static struct simplelock mntid_slock;
126 static struct simplelock vnode_free_list_slock;
127 static struct simplelock spechash_slock;
128 #endif
129 struct nfs_public nfs_pub;	/* publicly exported FS */
130 static vm_zone_t vnode_zone;
131 
132 /*
133  * The workitem queue.
134  */
135 #define SYNCER_MAXDELAY		32
136 static int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
137 time_t syncdelay = 30;		/* max time to delay syncing data */
138 time_t filedelay = 30;		/* time to delay syncing files */
139 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
140 time_t dirdelay = 29;		/* time to delay syncing directories */
141 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
142 time_t metadelay = 28;		/* time to delay syncing metadata */
143 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
144 static int rushjob;			/* number of slots to run ASAP */
145 static int stat_rush_requests;	/* number of times I/O speeded up */
146 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
147 
148 static int syncer_delayno = 0;
149 static long syncer_mask;
150 LIST_HEAD(synclist, vnode);
151 static struct synclist *syncer_workitem_pending;
152 
153 int desiredvnodes;
154 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
155     &desiredvnodes, 0, "Maximum number of vnodes");
156 
157 static void	vfs_free_addrlist __P((struct netexport *nep));
158 static int	vfs_free_netcred __P((struct radix_node *rn, void *w));
159 static int	vfs_hang_addrlist __P((struct mount *mp, struct netexport *nep,
160 				       struct export_args *argp));
161 
162 /*
163  * Initialize the vnode management data structures.
164  */
165 void
166 vntblinit()
167 {
168 
169 	desiredvnodes = maxproc + cnt.v_page_count / 4;
170 	simple_lock_init(&mntvnode_slock);
171 	simple_lock_init(&mntid_slock);
172 	simple_lock_init(&spechash_slock);
173 	TAILQ_INIT(&vnode_free_list);
174 	TAILQ_INIT(&vnode_tobefree_list);
175 	simple_lock_init(&vnode_free_list_slock);
176 	CIRCLEQ_INIT(&mountlist);
177 	vnode_zone = zinit("VNODE", sizeof (struct vnode), 0, 0, 5);
178 	/*
179 	 * Initialize the filesystem syncer.
180 	 */
181 	syncer_workitem_pending = hashinit(syncer_maxdelay, M_VNODE,
182 		&syncer_mask);
183 	syncer_maxdelay = syncer_mask + 1;
184 }
185 
186 /*
187  * Mark a mount point as busy. Used to synchronize access and to delay
188  * unmounting. Interlock is not released on failure.
189  */
190 int
191 vfs_busy(mp, flags, interlkp, p)
192 	struct mount *mp;
193 	int flags;
194 	struct simplelock *interlkp;
195 	struct proc *p;
196 {
197 	int lkflags;
198 
199 	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
200 		if (flags & LK_NOWAIT)
201 			return (ENOENT);
202 		mp->mnt_kern_flag |= MNTK_MWAIT;
203 		if (interlkp) {
204 			simple_unlock(interlkp);
205 		}
206 		/*
207 		 * Since all busy locks are shared except the exclusive
208 		 * lock granted when unmounting, the only place that a
209 		 * wakeup needs to be done is at the release of the
210 		 * exclusive lock at the end of dounmount.
211 		 */
212 		tsleep((caddr_t)mp, PVFS, "vfs_busy", 0);
213 		if (interlkp) {
214 			simple_lock(interlkp);
215 		}
216 		return (ENOENT);
217 	}
218 	lkflags = LK_SHARED | LK_NOPAUSE;
219 	if (interlkp)
220 		lkflags |= LK_INTERLOCK;
221 	if (lockmgr(&mp->mnt_lock, lkflags, interlkp, p))
222 		panic("vfs_busy: unexpected lock failure");
223 	return (0);
224 }
225 
226 /*
227  * Free a busy filesystem.
228  */
229 void
230 vfs_unbusy(mp, p)
231 	struct mount *mp;
232 	struct proc *p;
233 {
234 
235 	lockmgr(&mp->mnt_lock, LK_RELEASE, NULL, p);
236 }
237 
238 /*
239  * Lookup a filesystem type, and if found allocate and initialize
240  * a mount structure for it.
241  *
242  * Devname is usually updated by mount(8) after booting.
243  */
244 int
245 vfs_rootmountalloc(fstypename, devname, mpp)
246 	char *fstypename;
247 	char *devname;
248 	struct mount **mpp;
249 {
250 	struct proc *p = curproc;	/* XXX */
251 	struct vfsconf *vfsp;
252 	struct mount *mp;
253 
254 	if (fstypename == NULL)
255 		return (ENODEV);
256 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
257 		if (!strcmp(vfsp->vfc_name, fstypename))
258 			break;
259 	if (vfsp == NULL)
260 		return (ENODEV);
261 	mp = malloc((u_long)sizeof(struct mount), M_MOUNT, M_WAITOK);
262 	bzero((char *)mp, (u_long)sizeof(struct mount));
263 	lockinit(&mp->mnt_lock, PVFS, "vfslock", 0, LK_NOPAUSE);
264 	(void)vfs_busy(mp, LK_NOWAIT, 0, p);
265 	LIST_INIT(&mp->mnt_vnodelist);
266 	mp->mnt_vfc = vfsp;
267 	mp->mnt_op = vfsp->vfc_vfsops;
268 	mp->mnt_flag = MNT_RDONLY;
269 	mp->mnt_vnodecovered = NULLVP;
270 	vfsp->vfc_refcount++;
271 	mp->mnt_iosize_max = DFLTPHYS;
272 	mp->mnt_stat.f_type = vfsp->vfc_typenum;
273 	mp->mnt_flag |= vfsp->vfc_flags & MNT_VISFLAGMASK;
274 	strncpy(mp->mnt_stat.f_fstypename, vfsp->vfc_name, MFSNAMELEN);
275 	mp->mnt_stat.f_mntonname[0] = '/';
276 	mp->mnt_stat.f_mntonname[1] = 0;
277 	(void) copystr(devname, mp->mnt_stat.f_mntfromname, MNAMELEN - 1, 0);
278 	*mpp = mp;
279 	return (0);
280 }
281 
282 /*
283  * Find an appropriate filesystem to use for the root. If a filesystem
284  * has not been preselected, walk through the list of known filesystems
285  * trying those that have mountroot routines, and try them until one
286  * works or we have tried them all.
287  */
288 #ifdef notdef	/* XXX JH */
289 int
290 lite2_vfs_mountroot()
291 {
292 	struct vfsconf *vfsp;
293 	extern int (*lite2_mountroot) __P((void));
294 	int error;
295 
296 	if (lite2_mountroot != NULL)
297 		return ((*lite2_mountroot)());
298 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
299 		if (vfsp->vfc_mountroot == NULL)
300 			continue;
301 		if ((error = (*vfsp->vfc_mountroot)()) == 0)
302 			return (0);
303 		printf("%s_mountroot failed: %d\n", vfsp->vfc_name, error);
304 	}
305 	return (ENODEV);
306 }
307 #endif
308 
309 /*
310  * Lookup a mount point by filesystem identifier.
311  */
312 struct mount *
313 vfs_getvfs(fsid)
314 	fsid_t *fsid;
315 {
316 	register struct mount *mp;
317 
318 	simple_lock(&mountlist_slock);
319 	for (mp = mountlist.cqh_first; mp != (void *)&mountlist;
320 	    mp = mp->mnt_list.cqe_next) {
321 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
322 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
323 			simple_unlock(&mountlist_slock);
324 			return (mp);
325 	    }
326 	}
327 	simple_unlock(&mountlist_slock);
328 	return ((struct mount *) 0);
329 }
330 
331 /*
332  * Get a new unique fsid
333  *
334  * Keep in mind that several mounts may be running in parallel,
335  * so always increment mntid_base even if lower numbers are available.
336  */
337 
338 static u_short mntid_base;
339 
340 void
341 vfs_getnewfsid(mp)
342 	struct mount *mp;
343 {
344 	fsid_t tfsid;
345 	int mtype;
346 
347 	simple_lock(&mntid_slock);
348 
349 	mtype = mp->mnt_vfc->vfc_typenum;
350 	for (;;) {
351 		tfsid.val[0] = makeudev(255, mtype + (mntid_base << 16));
352 		tfsid.val[1] = mtype;
353 		++mntid_base;
354 		if (vfs_getvfs(&tfsid) == NULL)
355 			break;
356 	}
357 
358 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
359 	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
360 
361 	simple_unlock(&mntid_slock);
362 }
363 
364 /*
365  * Get what should become the root fsid.
366  *
367  * This is somewhat of a hack.  If the rootdev is not known we
368  * assume that vfs_getnewfsid() will be called momentarily to
369  * allocate it, and we return what vfs_getnewfsid() will return.
370  */
371 
372 dev_t
373 vfs_getrootfsid(struct mount *mp)
374 {
375 	int mtype;
376 
377 	mtype = mp->mnt_vfc->vfc_typenum;
378 	return(makedev(255, mtype + (mntid_base << 16)));
379 }
380 
381 /*
382  * Knob to control the precision of file timestamps:
383  *
384  *   0 = seconds only; nanoseconds zeroed.
385  *   1 = seconds and nanoseconds, accurate within 1/HZ.
386  *   2 = seconds and nanoseconds, truncated to microseconds.
387  * >=3 = seconds and nanoseconds, maximum precision.
388  */
389 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
390 
391 static int timestamp_precision = TSP_SEC;
392 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
393     &timestamp_precision, 0, "");
394 
395 /*
396  * Get a current timestamp.
397  */
398 void
399 vfs_timestamp(tsp)
400 	struct timespec *tsp;
401 {
402 	struct timeval tv;
403 
404 	switch (timestamp_precision) {
405 	case TSP_SEC:
406 		tsp->tv_sec = time_second;
407 		tsp->tv_nsec = 0;
408 		break;
409 	case TSP_HZ:
410 		getnanotime(tsp);
411 		break;
412 	case TSP_USEC:
413 		microtime(&tv);
414 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
415 		break;
416 	case TSP_NSEC:
417 	default:
418 		nanotime(tsp);
419 		break;
420 	}
421 }
422 
423 /*
424  * Set vnode attributes to VNOVAL
425  */
426 void
427 vattr_null(vap)
428 	register struct vattr *vap;
429 {
430 
431 	vap->va_type = VNON;
432 	vap->va_size = VNOVAL;
433 	vap->va_bytes = VNOVAL;
434 	vap->va_mode = VNOVAL;
435 	vap->va_nlink = VNOVAL;
436 	vap->va_uid = VNOVAL;
437 	vap->va_gid = VNOVAL;
438 	vap->va_fsid = VNOVAL;
439 	vap->va_fileid = VNOVAL;
440 	vap->va_blocksize = VNOVAL;
441 	vap->va_rdev = VNOVAL;
442 	vap->va_atime.tv_sec = VNOVAL;
443 	vap->va_atime.tv_nsec = VNOVAL;
444 	vap->va_mtime.tv_sec = VNOVAL;
445 	vap->va_mtime.tv_nsec = VNOVAL;
446 	vap->va_ctime.tv_sec = VNOVAL;
447 	vap->va_ctime.tv_nsec = VNOVAL;
448 	vap->va_flags = VNOVAL;
449 	vap->va_gen = VNOVAL;
450 	vap->va_vaflags = 0;
451 }
452 
453 /*
454  * Routines having to do with the management of the vnode table.
455  */
456 extern vop_t **dead_vnodeop_p;
457 
458 /*
459  * Return the next vnode from the free list.
460  */
461 int
462 getnewvnode(tag, mp, vops, vpp)
463 	enum vtagtype tag;
464 	struct mount *mp;
465 	vop_t **vops;
466 	struct vnode **vpp;
467 {
468 	int s;
469 	struct proc *p = curproc;	/* XXX */
470 	struct vnode *vp, *tvp, *nvp;
471 	vm_object_t object;
472 	TAILQ_HEAD(freelst, vnode) vnode_tmp_list;
473 
474 	/*
475 	 * We take the least recently used vnode from the freelist
476 	 * if we can get it and it has no cached pages, and no
477 	 * namecache entries are relative to it.
478 	 * Otherwise we allocate a new vnode
479 	 */
480 
481 	s = splbio();
482 	simple_lock(&vnode_free_list_slock);
483 	TAILQ_INIT(&vnode_tmp_list);
484 
485 	for (vp = TAILQ_FIRST(&vnode_tobefree_list); vp; vp = nvp) {
486 		nvp = TAILQ_NEXT(vp, v_freelist);
487 		TAILQ_REMOVE(&vnode_tobefree_list, vp, v_freelist);
488 		if (vp->v_flag & VAGE) {
489 			TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
490 		} else {
491 			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
492 		}
493 		vp->v_flag &= ~(VTBFREE|VAGE);
494 		vp->v_flag |= VFREE;
495 		if (vp->v_usecount)
496 			panic("tobe free vnode isn't");
497 		freevnodes++;
498 	}
499 
500 	if (wantfreevnodes && freevnodes < wantfreevnodes) {
501 		vp = NULL;
502 	} else if (!wantfreevnodes && freevnodes <= desiredvnodes) {
503 		/*
504 		 * XXX: this is only here to be backwards compatible
505 		 */
506 		vp = NULL;
507 	} else {
508 		for (vp = TAILQ_FIRST(&vnode_free_list); vp; vp = nvp) {
509 			nvp = TAILQ_NEXT(vp, v_freelist);
510 			if (!simple_lock_try(&vp->v_interlock))
511 				continue;
512 			if (vp->v_usecount)
513 				panic("free vnode isn't");
514 
515 			object = vp->v_object;
516 			if (object && (object->resident_page_count || object->ref_count)) {
517 				printf("object inconsistant state: RPC: %d, RC: %d\n",
518 					object->resident_page_count, object->ref_count);
519 				/* Don't recycle if it's caching some pages */
520 				TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
521 				TAILQ_INSERT_TAIL(&vnode_tmp_list, vp, v_freelist);
522 				continue;
523 			} else if (LIST_FIRST(&vp->v_cache_src)) {
524 				/* Don't recycle if active in the namecache */
525 				simple_unlock(&vp->v_interlock);
526 				continue;
527 			} else {
528 				break;
529 			}
530 		}
531 	}
532 
533 	for (tvp = TAILQ_FIRST(&vnode_tmp_list); tvp; tvp = nvp) {
534 		nvp = TAILQ_NEXT(tvp, v_freelist);
535 		TAILQ_REMOVE(&vnode_tmp_list, tvp, v_freelist);
536 		TAILQ_INSERT_TAIL(&vnode_free_list, tvp, v_freelist);
537 		simple_unlock(&tvp->v_interlock);
538 	}
539 
540 	if (vp) {
541 		vp->v_flag |= VDOOMED;
542 		TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
543 		freevnodes--;
544 		simple_unlock(&vnode_free_list_slock);
545 		cache_purge(vp);
546 		vp->v_lease = NULL;
547 		if (vp->v_type != VBAD) {
548 			vgonel(vp, p);
549 		} else {
550 			simple_unlock(&vp->v_interlock);
551 		}
552 
553 #ifdef INVARIANTS
554 		{
555 			int s;
556 
557 			if (vp->v_data)
558 				panic("cleaned vnode isn't");
559 			s = splbio();
560 			if (vp->v_numoutput)
561 				panic("Clean vnode has pending I/O's");
562 			splx(s);
563 		}
564 #endif
565 		vp->v_flag = 0;
566 		vp->v_lastw = 0;
567 		vp->v_lasta = 0;
568 		vp->v_cstart = 0;
569 		vp->v_clen = 0;
570 		vp->v_socket = 0;
571 		vp->v_writecount = 0;	/* XXX */
572 	} else {
573 		simple_unlock(&vnode_free_list_slock);
574 		vp = (struct vnode *) zalloc(vnode_zone);
575 		bzero((char *) vp, sizeof *vp);
576 		simple_lock_init(&vp->v_interlock);
577 		vp->v_dd = vp;
578 		cache_purge(vp);
579 		LIST_INIT(&vp->v_cache_src);
580 		TAILQ_INIT(&vp->v_cache_dst);
581 		numvnodes++;
582 	}
583 
584 	TAILQ_INIT(&vp->v_cleanblkhd);
585 	TAILQ_INIT(&vp->v_dirtyblkhd);
586 	vp->v_type = VNON;
587 	vp->v_tag = tag;
588 	vp->v_op = vops;
589 	insmntque(vp, mp);
590 	*vpp = vp;
591 	vp->v_usecount = 1;
592 	vp->v_data = 0;
593 	splx(s);
594 
595 	vfs_object_create(vp, p, p->p_ucred);
596 	return (0);
597 }
598 
599 /*
600  * Move a vnode from one mount queue to another.
601  */
602 static void
603 insmntque(vp, mp)
604 	register struct vnode *vp;
605 	register struct mount *mp;
606 {
607 
608 	simple_lock(&mntvnode_slock);
609 	/*
610 	 * Delete from old mount point vnode list, if on one.
611 	 */
612 	if (vp->v_mount != NULL)
613 		LIST_REMOVE(vp, v_mntvnodes);
614 	/*
615 	 * Insert into list of vnodes for the new mount point, if available.
616 	 */
617 	if ((vp->v_mount = mp) == NULL) {
618 		simple_unlock(&mntvnode_slock);
619 		return;
620 	}
621 	LIST_INSERT_HEAD(&mp->mnt_vnodelist, vp, v_mntvnodes);
622 	simple_unlock(&mntvnode_slock);
623 }
624 
625 /*
626  * Update outstanding I/O count and do wakeup if requested.
627  */
628 void
629 vwakeup(bp)
630 	register struct buf *bp;
631 {
632 	register struct vnode *vp;
633 
634 	bp->b_flags &= ~B_WRITEINPROG;
635 	if ((vp = bp->b_vp)) {
636 		vp->v_numoutput--;
637 		if (vp->v_numoutput < 0)
638 			panic("vwakeup: neg numoutput");
639 		if ((vp->v_numoutput == 0) && (vp->v_flag & VBWAIT)) {
640 			vp->v_flag &= ~VBWAIT;
641 			wakeup((caddr_t) &vp->v_numoutput);
642 		}
643 	}
644 }
645 
646 /*
647  * Flush out and invalidate all buffers associated with a vnode.
648  * Called with the underlying object locked.
649  */
650 int
651 vinvalbuf(vp, flags, cred, p, slpflag, slptimeo)
652 	register struct vnode *vp;
653 	int flags;
654 	struct ucred *cred;
655 	struct proc *p;
656 	int slpflag, slptimeo;
657 {
658 	register struct buf *bp;
659 	struct buf *nbp, *blist;
660 	int s, error;
661 	vm_object_t object;
662 
663 	if (flags & V_SAVE) {
664 		s = splbio();
665 		while (vp->v_numoutput) {
666 			vp->v_flag |= VBWAIT;
667 			error = tsleep((caddr_t)&vp->v_numoutput,
668 			    slpflag | (PRIBIO + 1), "vinvlbuf", slptimeo);
669 			if (error) {
670 				splx(s);
671 				return (error);
672 			}
673 		}
674 		if (!TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
675 			splx(s);
676 			if ((error = VOP_FSYNC(vp, cred, MNT_WAIT, p)) != 0)
677 				return (error);
678 			s = splbio();
679 			if (vp->v_numoutput > 0 ||
680 			    !TAILQ_EMPTY(&vp->v_dirtyblkhd))
681 				panic("vinvalbuf: dirty bufs");
682 		}
683 		splx(s);
684   	}
685 	s = splbio();
686 	for (;;) {
687 		blist = TAILQ_FIRST(&vp->v_cleanblkhd);
688 		if (!blist)
689 			blist = TAILQ_FIRST(&vp->v_dirtyblkhd);
690 		if (!blist)
691 			break;
692 
693 		for (bp = blist; bp; bp = nbp) {
694 			nbp = TAILQ_NEXT(bp, b_vnbufs);
695 			if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
696 				error = BUF_TIMELOCK(bp,
697 				    LK_EXCLUSIVE | LK_SLEEPFAIL,
698 				    "vinvalbuf", slpflag, slptimeo);
699 				if (error == ENOLCK)
700 					break;
701 				splx(s);
702 				return (error);
703 			}
704 			/*
705 			 * XXX Since there are no node locks for NFS, I
706 			 * believe there is a slight chance that a delayed
707 			 * write will occur while sleeping just above, so
708 			 * check for it.  Note that vfs_bio_awrite expects
709 			 * buffers to reside on a queue, while VOP_BWRITE and
710 			 * brelse do not.
711 			 */
712 			if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
713 				(flags & V_SAVE)) {
714 
715 				if (bp->b_vp == vp) {
716 					if (bp->b_flags & B_CLUSTEROK) {
717 						BUF_UNLOCK(bp);
718 						vfs_bio_awrite(bp);
719 					} else {
720 						bremfree(bp);
721 						bp->b_flags |= B_ASYNC;
722 						VOP_BWRITE(bp->b_vp, bp);
723 					}
724 				} else {
725 					bremfree(bp);
726 					(void) VOP_BWRITE(bp->b_vp, bp);
727 				}
728 				break;
729 			}
730 			bremfree(bp);
731 			bp->b_flags |= (B_INVAL | B_NOCACHE | B_RELBUF);
732 			bp->b_flags &= ~B_ASYNC;
733 			brelse(bp);
734 		}
735 	}
736 
737 	while (vp->v_numoutput > 0) {
738 		vp->v_flag |= VBWAIT;
739 		tsleep(&vp->v_numoutput, PVM, "vnvlbv", 0);
740 	}
741 
742 	splx(s);
743 
744 	/*
745 	 * Destroy the copy in the VM cache, too.
746 	 */
747 	simple_lock(&vp->v_interlock);
748 	object = vp->v_object;
749 	if (object != NULL) {
750 		vm_object_page_remove(object, 0, 0,
751 			(flags & V_SAVE) ? TRUE : FALSE);
752 	}
753 	simple_unlock(&vp->v_interlock);
754 
755 	if (!TAILQ_EMPTY(&vp->v_dirtyblkhd) || !TAILQ_EMPTY(&vp->v_cleanblkhd))
756 		panic("vinvalbuf: flush failed");
757 	return (0);
758 }
759 
760 /*
761  * Truncate a file's buffer and pages to a specified length.  This
762  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
763  * sync activity.
764  */
765 int
766 vtruncbuf(vp, cred, p, length, blksize)
767 	register struct vnode *vp;
768 	struct ucred *cred;
769 	struct proc *p;
770 	off_t length;
771 	int blksize;
772 {
773 	register struct buf *bp;
774 	struct buf *nbp;
775 	int s, anyfreed;
776 	int trunclbn;
777 
778 	/*
779 	 * Round up to the *next* lbn.
780 	 */
781 	trunclbn = (length + blksize - 1) / blksize;
782 
783 	s = splbio();
784 restart:
785 	anyfreed = 1;
786 	for (;anyfreed;) {
787 		anyfreed = 0;
788 		for (bp = TAILQ_FIRST(&vp->v_cleanblkhd); bp; bp = nbp) {
789 			nbp = TAILQ_NEXT(bp, b_vnbufs);
790 			if (bp->b_lblkno >= trunclbn) {
791 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
792 					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
793 					goto restart;
794 				} else {
795 					bremfree(bp);
796 					bp->b_flags |= (B_INVAL | B_RELBUF);
797 					bp->b_flags &= ~B_ASYNC;
798 					brelse(bp);
799 					anyfreed = 1;
800 				}
801 				if (nbp && (((nbp->b_xflags & B_VNCLEAN) == 0)||
802 					 (nbp->b_vp != vp) ||
803 					 (nbp->b_flags & B_DELWRI))) {
804 					goto restart;
805 				}
806 			}
807 		}
808 
809 		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
810 			nbp = TAILQ_NEXT(bp, b_vnbufs);
811 			if (bp->b_lblkno >= trunclbn) {
812 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
813 					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
814 					goto restart;
815 				} else {
816 					bremfree(bp);
817 					bp->b_flags |= (B_INVAL | B_RELBUF);
818 					bp->b_flags &= ~B_ASYNC;
819 					brelse(bp);
820 					anyfreed = 1;
821 				}
822 				if (nbp && (((nbp->b_xflags & B_VNDIRTY) == 0)||
823 					 (nbp->b_vp != vp) ||
824 					 (nbp->b_flags & B_DELWRI) == 0)) {
825 					goto restart;
826 				}
827 			}
828 		}
829 	}
830 
831 	if (length > 0) {
832 restartsync:
833 		for (bp = TAILQ_FIRST(&vp->v_dirtyblkhd); bp; bp = nbp) {
834 			nbp = TAILQ_NEXT(bp, b_vnbufs);
835 			if ((bp->b_flags & B_DELWRI) && (bp->b_lblkno < 0)) {
836 				if (BUF_LOCK(bp, LK_EXCLUSIVE | LK_NOWAIT)) {
837 					BUF_LOCK(bp, LK_EXCLUSIVE|LK_SLEEPFAIL);
838 					goto restart;
839 				} else {
840 					bremfree(bp);
841 					if (bp->b_vp == vp) {
842 						bp->b_flags |= B_ASYNC;
843 					} else {
844 						bp->b_flags &= ~B_ASYNC;
845 					}
846 					VOP_BWRITE(bp->b_vp, bp);
847 				}
848 				goto restartsync;
849 			}
850 
851 		}
852 	}
853 
854 	while (vp->v_numoutput > 0) {
855 		vp->v_flag |= VBWAIT;
856 		tsleep(&vp->v_numoutput, PVM, "vbtrunc", 0);
857 	}
858 
859 	splx(s);
860 
861 	vnode_pager_setsize(vp, length);
862 
863 	return (0);
864 }
865 
866 /*
867  * Associate a buffer with a vnode.
868  */
869 void
870 bgetvp(vp, bp)
871 	register struct vnode *vp;
872 	register struct buf *bp;
873 {
874 	int s;
875 
876 	KASSERT(bp->b_vp == NULL, ("bgetvp: not free"));
877 
878 	vhold(vp);
879 	bp->b_vp = vp;
880 	bp->b_dev = vn_todev(vp);
881 	/*
882 	 * Insert onto list for new vnode.
883 	 */
884 	s = splbio();
885 	bp->b_xflags |= B_VNCLEAN;
886 	bp->b_xflags &= ~B_VNDIRTY;
887 	TAILQ_INSERT_TAIL(&vp->v_cleanblkhd, bp, b_vnbufs);
888 	splx(s);
889 }
890 
891 /*
892  * Disassociate a buffer from a vnode.
893  */
894 void
895 brelvp(bp)
896 	register struct buf *bp;
897 {
898 	struct vnode *vp;
899 	struct buflists *listheadp;
900 	int s;
901 
902 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
903 
904 	/*
905 	 * Delete from old vnode list, if on one.
906 	 */
907 	vp = bp->b_vp;
908 	s = splbio();
909 	if (bp->b_xflags & (B_VNDIRTY|B_VNCLEAN)) {
910 		if (bp->b_xflags & B_VNDIRTY)
911 			listheadp = &vp->v_dirtyblkhd;
912 		else
913 			listheadp = &vp->v_cleanblkhd;
914 		TAILQ_REMOVE(listheadp, bp, b_vnbufs);
915 		bp->b_xflags &= ~(B_VNDIRTY|B_VNCLEAN);
916 	}
917 	if ((vp->v_flag & VONWORKLST) && TAILQ_EMPTY(&vp->v_dirtyblkhd)) {
918 		vp->v_flag &= ~VONWORKLST;
919 		LIST_REMOVE(vp, v_synclist);
920 	}
921 	splx(s);
922 	bp->b_vp = (struct vnode *) 0;
923 	vdrop(vp);
924 }
925 
926 /*
927  * The workitem queue.
928  *
929  * It is useful to delay writes of file data and filesystem metadata
930  * for tens of seconds so that quickly created and deleted files need
931  * not waste disk bandwidth being created and removed. To realize this,
932  * we append vnodes to a "workitem" queue. When running with a soft
933  * updates implementation, most pending metadata dependencies should
934  * not wait for more than a few seconds. Thus, mounted on block devices
935  * are delayed only about a half the time that file data is delayed.
936  * Similarly, directory updates are more critical, so are only delayed
937  * about a third the time that file data is delayed. Thus, there are
938  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
939  * one each second (driven off the filesystem syncer process). The
940  * syncer_delayno variable indicates the next queue that is to be processed.
941  * Items that need to be processed soon are placed in this queue:
942  *
943  *	syncer_workitem_pending[syncer_delayno]
944  *
945  * A delay of fifteen seconds is done by placing the request fifteen
946  * entries later in the queue:
947  *
948  *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
949  *
950  */
951 
952 /*
953  * Add an item to the syncer work queue.
954  */
955 static void
956 vn_syncer_add_to_worklist(struct vnode *vp, int delay)
957 {
958 	int s, slot;
959 
960 	s = splbio();
961 
962 	if (vp->v_flag & VONWORKLST) {
963 		LIST_REMOVE(vp, v_synclist);
964 	}
965 
966 	if (delay > syncer_maxdelay - 2)
967 		delay = syncer_maxdelay - 2;
968 	slot = (syncer_delayno + delay) & syncer_mask;
969 
970 	LIST_INSERT_HEAD(&syncer_workitem_pending[slot], vp, v_synclist);
971 	vp->v_flag |= VONWORKLST;
972 	splx(s);
973 }
974 
975 struct  proc *updateproc;
976 static void sched_sync __P((void));
977 static struct kproc_desc up_kp = {
978 	"syncer",
979 	sched_sync,
980 	&updateproc
981 };
982 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp)
983 
984 /*
985  * System filesystem synchronizer daemon.
986  */
987 void
988 sched_sync(void)
989 {
990 	struct synclist *slp;
991 	struct vnode *vp;
992 	long starttime;
993 	int s;
994 	struct proc *p = updateproc;
995 
996 	p->p_flag |= P_BUFEXHAUST;
997 
998 	for (;;) {
999 		starttime = time_second;
1000 
1001 		/*
1002 		 * Push files whose dirty time has expired.  Be careful
1003 		 * of interrupt race on slp queue.
1004 		 */
1005 		s = splbio();
1006 		slp = &syncer_workitem_pending[syncer_delayno];
1007 		syncer_delayno += 1;
1008 		if (syncer_delayno == syncer_maxdelay)
1009 			syncer_delayno = 0;
1010 		splx(s);
1011 
1012 		while ((vp = LIST_FIRST(slp)) != NULL) {
1013 			if (VOP_ISLOCKED(vp) == 0) {
1014 				vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
1015 				(void) VOP_FSYNC(vp, p->p_ucred, MNT_LAZY, p);
1016 				VOP_UNLOCK(vp, 0, p);
1017 			}
1018 			s = splbio();
1019 			if (LIST_FIRST(slp) == vp) {
1020 				/*
1021 				 * Note: v_tag VT_VFS vps can remain on the
1022 				 * worklist too with no dirty blocks, but
1023 				 * since sync_fsync() moves it to a different
1024 				 * slot we are safe.
1025 				 */
1026 				if (TAILQ_EMPTY(&vp->v_dirtyblkhd) &&
1027 				    vp->v_type != VBLK)
1028 					panic("sched_sync: fsync failed vp %p tag %d", vp, vp->v_tag);
1029 				/*
1030 				 * Put us back on the worklist.  The worklist
1031 				 * routine will remove us from our current
1032 				 * position and then add us back in at a later
1033 				 * position.
1034 				 */
1035 				vn_syncer_add_to_worklist(vp, syncdelay);
1036 			}
1037 			splx(s);
1038 		}
1039 
1040 		/*
1041 		 * Do soft update processing.
1042 		 */
1043 		if (bioops.io_sync)
1044 			(*bioops.io_sync)(NULL);
1045 
1046 		/*
1047 		 * The variable rushjob allows the kernel to speed up the
1048 		 * processing of the filesystem syncer process. A rushjob
1049 		 * value of N tells the filesystem syncer to process the next
1050 		 * N seconds worth of work on its queue ASAP. Currently rushjob
1051 		 * is used by the soft update code to speed up the filesystem
1052 		 * syncer process when the incore state is getting so far
1053 		 * ahead of the disk that the kernel memory pool is being
1054 		 * threatened with exhaustion.
1055 		 */
1056 		if (rushjob > 0) {
1057 			rushjob -= 1;
1058 			continue;
1059 		}
1060 		/*
1061 		 * If it has taken us less than a second to process the
1062 		 * current work, then wait. Otherwise start right over
1063 		 * again. We can still lose time if any single round
1064 		 * takes more than two seconds, but it does not really
1065 		 * matter as we are just trying to generally pace the
1066 		 * filesystem activity.
1067 		 */
1068 		if (time_second == starttime)
1069 			tsleep(&lbolt, PPAUSE, "syncer", 0);
1070 	}
1071 }
1072 
1073 /*
1074  * Request the syncer daemon to speed up its work.
1075  * We never push it to speed up more than half of its
1076  * normal turn time, otherwise it could take over the cpu.
1077  */
1078 int
1079 speedup_syncer()
1080 {
1081 	int s;
1082 
1083 	s = splhigh();
1084 	if (updateproc->p_wchan == &lbolt)
1085 		setrunnable(updateproc);
1086 	splx(s);
1087 	if (rushjob < syncdelay / 2) {
1088 		rushjob += 1;
1089 		stat_rush_requests += 1;
1090 		return (1);
1091 	}
1092 	return(0);
1093 }
1094 
1095 /*
1096  * Associate a p-buffer with a vnode.
1097  *
1098  * Also sets B_PAGING flag to indicate that vnode is not fully associated
1099  * with the buffer.  i.e. the bp has not been linked into the vnode or
1100  * ref-counted.
1101  */
1102 void
1103 pbgetvp(vp, bp)
1104 	register struct vnode *vp;
1105 	register struct buf *bp;
1106 {
1107 
1108 	KASSERT(bp->b_vp == NULL, ("pbgetvp: not free"));
1109 
1110 	bp->b_vp = vp;
1111 	bp->b_flags |= B_PAGING;
1112 	bp->b_dev = vn_todev(vp);
1113 }
1114 
1115 /*
1116  * Disassociate a p-buffer from a vnode.
1117  */
1118 void
1119 pbrelvp(bp)
1120 	register struct buf *bp;
1121 {
1122 
1123 	KASSERT(bp->b_vp != NULL, ("pbrelvp: NULL"));
1124 
1125 #if !defined(MAX_PERF)
1126 	/* XXX REMOVE ME */
1127 	if (bp->b_vnbufs.tqe_next != NULL) {
1128 		panic(
1129 		    "relpbuf(): b_vp was probably reassignbuf()d %p %x",
1130 		    bp,
1131 		    (int)bp->b_flags
1132 		);
1133 	}
1134 #endif
1135 	bp->b_vp = (struct vnode *) 0;
1136 	bp->b_flags &= ~B_PAGING;
1137 }
1138 
1139 void
1140 pbreassignbuf(bp, newvp)
1141 	struct buf *bp;
1142 	struct vnode *newvp;
1143 {
1144 #if !defined(MAX_PERF)
1145 	if ((bp->b_flags & B_PAGING) == 0) {
1146 		panic(
1147 		    "pbreassignbuf() on non phys bp %p",
1148 		    bp
1149 		);
1150 	}
1151 #endif
1152 	bp->b_vp = newvp;
1153 }
1154 
1155 /*
1156  * Reassign a buffer from one vnode to another.
1157  * Used to assign file specific control information
1158  * (indirect blocks) to the vnode to which they belong.
1159  */
1160 void
1161 reassignbuf(bp, newvp)
1162 	register struct buf *bp;
1163 	register struct vnode *newvp;
1164 {
1165 	struct buflists *listheadp;
1166 	int delay;
1167 	int s;
1168 
1169 	if (newvp == NULL) {
1170 		printf("reassignbuf: NULL");
1171 		return;
1172 	}
1173 	++reassignbufcalls;
1174 
1175 #if !defined(MAX_PERF)
1176 	/*
1177 	 * B_PAGING flagged buffers cannot be reassigned because their vp
1178 	 * is not fully linked in.
1179 	 */
1180 	if (bp->b_flags & B_PAGING)
1181 		panic("cannot reassign paging buffer");
1182 #endif
1183 
1184 	s = splbio();
1185 	/*
1186 	 * Delete from old vnode list, if on one.
1187 	 */
1188 	if (bp->b_xflags & (B_VNDIRTY|B_VNCLEAN)) {
1189 		if (bp->b_xflags & B_VNDIRTY)
1190 			listheadp = &bp->b_vp->v_dirtyblkhd;
1191 		else
1192 			listheadp = &bp->b_vp->v_cleanblkhd;
1193 		TAILQ_REMOVE(listheadp, bp, b_vnbufs);
1194 		bp->b_xflags &= ~(B_VNDIRTY|B_VNCLEAN);
1195 		if (bp->b_vp != newvp) {
1196 			vdrop(bp->b_vp);
1197 			bp->b_vp = NULL;	/* for clarification */
1198 		}
1199 	}
1200 	/*
1201 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1202 	 * of clean buffers.
1203 	 */
1204 	if (bp->b_flags & B_DELWRI) {
1205 		struct buf *tbp;
1206 
1207 		listheadp = &newvp->v_dirtyblkhd;
1208 		if ((newvp->v_flag & VONWORKLST) == 0) {
1209 			switch (newvp->v_type) {
1210 			case VDIR:
1211 				delay = dirdelay;
1212 				break;
1213 			case VBLK:
1214 				if (newvp->v_specmountpoint != NULL) {
1215 					delay = metadelay;
1216 					break;
1217 				}
1218 				/* fall through */
1219 			default:
1220 				delay = filedelay;
1221 			}
1222 			vn_syncer_add_to_worklist(newvp, delay);
1223 		}
1224 		bp->b_xflags |= B_VNDIRTY;
1225 		tbp = TAILQ_FIRST(listheadp);
1226 		if (tbp == NULL ||
1227 		    bp->b_lblkno == 0 ||
1228 		    (bp->b_lblkno > 0 && bp->b_lblkno < tbp->b_lblkno)) {
1229 			TAILQ_INSERT_HEAD(listheadp, bp, b_vnbufs);
1230 			++reassignbufsortgood;
1231 		} else if (bp->b_lblkno < 0) {
1232 			TAILQ_INSERT_TAIL(listheadp, bp, b_vnbufs);
1233 			++reassignbufsortgood;
1234 		} else if (reassignbufmethod == 1) {
1235 			/*
1236 			 * New sorting algorithm, only handle sequential case,
1237 			 * otherwise guess.
1238 			 */
1239 			if ((tbp = gbincore(newvp, bp->b_lblkno - 1)) != NULL &&
1240 			    (tbp->b_xflags & B_VNDIRTY)) {
1241 				TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1242 				++reassignbufsortgood;
1243 			} else {
1244 				TAILQ_INSERT_HEAD(listheadp, bp, b_vnbufs);
1245 				++reassignbufsortbad;
1246 			}
1247 		} else {
1248 			/*
1249 			 * Old sorting algorithm, scan queue and insert
1250 			 */
1251 			struct buf *ttbp;
1252 			while ((ttbp = TAILQ_NEXT(tbp, b_vnbufs)) &&
1253 			    (ttbp->b_lblkno < bp->b_lblkno)) {
1254 				++reassignbufloops;
1255 				tbp = ttbp;
1256 			}
1257 			TAILQ_INSERT_AFTER(listheadp, tbp, bp, b_vnbufs);
1258 		}
1259 	} else {
1260 		bp->b_xflags |= B_VNCLEAN;
1261 		TAILQ_INSERT_TAIL(&newvp->v_cleanblkhd, bp, b_vnbufs);
1262 		if ((newvp->v_flag & VONWORKLST) &&
1263 		    TAILQ_EMPTY(&newvp->v_dirtyblkhd)) {
1264 			newvp->v_flag &= ~VONWORKLST;
1265 			LIST_REMOVE(newvp, v_synclist);
1266 		}
1267 	}
1268 	if (bp->b_vp != newvp) {
1269 		bp->b_vp = newvp;
1270 		vhold(bp->b_vp);
1271 	}
1272 	splx(s);
1273 }
1274 
1275 /*
1276  * Create a vnode for a block device.
1277  * Used for mounting the root file system.
1278  */
1279 int
1280 bdevvp(dev, vpp)
1281 	dev_t dev;
1282 	struct vnode **vpp;
1283 {
1284 	register struct vnode *vp;
1285 	struct vnode *nvp;
1286 	int error;
1287 
1288 	if (dev == NODEV) {
1289 		*vpp = NULLVP;
1290 		return (ENXIO);
1291 	}
1292 	error = getnewvnode(VT_NON, (struct mount *)0, spec_vnodeop_p, &nvp);
1293 	if (error) {
1294 		*vpp = NULLVP;
1295 		return (error);
1296 	}
1297 	vp = nvp;
1298 	vp->v_type = VBLK;
1299 	addalias(vp, dev);
1300 	*vpp = vp;
1301 	return (0);
1302 }
1303 
1304 /*
1305  * Add vnode to the alias list hung off the dev_t.
1306  *
1307  * The reason for this gunk is that multiple vnodes can reference
1308  * the same physical device, so checking vp->v_usecount to see
1309  * how many users there are is inadequate; the v_usecount for
1310  * the vnodes need to be accumulated.  vcount() does that.
1311  */
1312 void
1313 addaliasu(nvp, nvp_rdev)
1314 	struct vnode *nvp;
1315 	udev_t nvp_rdev;
1316 {
1317 
1318 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1319 		panic("addaliasu on non-special vnode");
1320 	addalias(nvp, udev2dev(nvp_rdev, nvp->v_type == VBLK ? 1 : 0));
1321 }
1322 
1323 void
1324 addalias(nvp, dev)
1325 	struct vnode *nvp;
1326 	dev_t dev;
1327 {
1328 
1329 	if (nvp->v_type != VBLK && nvp->v_type != VCHR)
1330 		panic("addalias on non-special vnode");
1331 
1332 	nvp->v_rdev = dev;
1333 	simple_lock(&spechash_slock);
1334 	SLIST_INSERT_HEAD(&dev->si_hlist, nvp, v_specnext);
1335 	simple_unlock(&spechash_slock);
1336 }
1337 
1338 /*
1339  * Grab a particular vnode from the free list, increment its
1340  * reference count and lock it. The vnode lock bit is set if the
1341  * vnode is being eliminated in vgone. The process is awakened
1342  * when the transition is completed, and an error returned to
1343  * indicate that the vnode is no longer usable (possibly having
1344  * been changed to a new file system type).
1345  */
1346 int
1347 vget(vp, flags, p)
1348 	register struct vnode *vp;
1349 	int flags;
1350 	struct proc *p;
1351 {
1352 	int error;
1353 
1354 	/*
1355 	 * If the vnode is in the process of being cleaned out for
1356 	 * another use, we wait for the cleaning to finish and then
1357 	 * return failure. Cleaning is determined by checking that
1358 	 * the VXLOCK flag is set.
1359 	 */
1360 	if ((flags & LK_INTERLOCK) == 0) {
1361 		simple_lock(&vp->v_interlock);
1362 	}
1363 	if (vp->v_flag & VXLOCK) {
1364 		vp->v_flag |= VXWANT;
1365 		simple_unlock(&vp->v_interlock);
1366 		tsleep((caddr_t)vp, PINOD, "vget", 0);
1367 		return (ENOENT);
1368 	}
1369 
1370 	vp->v_usecount++;
1371 
1372 	if (VSHOULDBUSY(vp))
1373 		vbusy(vp);
1374 	if (flags & LK_TYPE_MASK) {
1375 		if ((error = vn_lock(vp, flags | LK_INTERLOCK, p)) != 0) {
1376 			/*
1377 			 * must expand vrele here because we do not want
1378 			 * to call VOP_INACTIVE if the reference count
1379 			 * drops back to zero since it was never really
1380 			 * active. We must remove it from the free list
1381 			 * before sleeping so that multiple processes do
1382 			 * not try to recycle it.
1383 			 */
1384 			simple_lock(&vp->v_interlock);
1385 			vp->v_usecount--;
1386 			if (VSHOULDFREE(vp))
1387 				vfree(vp);
1388 			simple_unlock(&vp->v_interlock);
1389 		}
1390 		return (error);
1391 	}
1392 	simple_unlock(&vp->v_interlock);
1393 	return (0);
1394 }
1395 
1396 void
1397 vref(struct vnode *vp)
1398 {
1399 	simple_lock(&vp->v_interlock);
1400 	vp->v_usecount++;
1401 	simple_unlock(&vp->v_interlock);
1402 }
1403 
1404 /*
1405  * Vnode put/release.
1406  * If count drops to zero, call inactive routine and return to freelist.
1407  */
1408 void
1409 vrele(vp)
1410 	struct vnode *vp;
1411 {
1412 	struct proc *p = curproc;	/* XXX */
1413 
1414 	KASSERT(vp != NULL, ("vrele: null vp"));
1415 
1416 	simple_lock(&vp->v_interlock);
1417 
1418 	if (vp->v_usecount > 1) {
1419 
1420 		vp->v_usecount--;
1421 		simple_unlock(&vp->v_interlock);
1422 
1423 		return;
1424 	}
1425 
1426 	if (vp->v_usecount == 1) {
1427 
1428 		vp->v_usecount--;
1429 		if (VSHOULDFREE(vp))
1430 			vfree(vp);
1431 	/*
1432 	 * If we are doing a vput, the node is already locked, and we must
1433 	 * call VOP_INACTIVE with the node locked.  So, in the case of
1434 	 * vrele, we explicitly lock the vnode before calling VOP_INACTIVE.
1435 	 */
1436 		if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, p) == 0) {
1437 			VOP_INACTIVE(vp, p);
1438 		}
1439 
1440 	} else {
1441 #ifdef DIAGNOSTIC
1442 		vprint("vrele: negative ref count", vp);
1443 		simple_unlock(&vp->v_interlock);
1444 #endif
1445 		panic("vrele: negative ref cnt");
1446 	}
1447 }
1448 
1449 void
1450 vput(vp)
1451 	struct vnode *vp;
1452 {
1453 	struct proc *p = curproc;	/* XXX */
1454 
1455 	KASSERT(vp != NULL, ("vput: null vp"));
1456 
1457 	simple_lock(&vp->v_interlock);
1458 
1459 	if (vp->v_usecount > 1) {
1460 
1461 		vp->v_usecount--;
1462 		VOP_UNLOCK(vp, LK_INTERLOCK, p);
1463 		return;
1464 
1465 	}
1466 
1467 	if (vp->v_usecount == 1) {
1468 
1469 		vp->v_usecount--;
1470 		if (VSHOULDFREE(vp))
1471 			vfree(vp);
1472 	/*
1473 	 * If we are doing a vput, the node is already locked, and we must
1474 	 * call VOP_INACTIVE with the node locked.  So, in the case of
1475 	 * vrele, we explicitly lock the vnode before calling VOP_INACTIVE.
1476 	 */
1477 		simple_unlock(&vp->v_interlock);
1478 		VOP_INACTIVE(vp, p);
1479 
1480 	} else {
1481 #ifdef DIAGNOSTIC
1482 		vprint("vput: negative ref count", vp);
1483 #endif
1484 		panic("vput: negative ref cnt");
1485 	}
1486 }
1487 
1488 /*
1489  * Somebody doesn't want the vnode recycled.
1490  */
1491 void
1492 vhold(vp)
1493 	register struct vnode *vp;
1494 {
1495 	int s;
1496 
1497   	s = splbio();
1498 	vp->v_holdcnt++;
1499 	if (VSHOULDBUSY(vp))
1500 		vbusy(vp);
1501 	splx(s);
1502 }
1503 
1504 /*
1505  * One less who cares about this vnode.
1506  */
1507 void
1508 vdrop(vp)
1509 	register struct vnode *vp;
1510 {
1511 	int s;
1512 
1513 	s = splbio();
1514 	if (vp->v_holdcnt <= 0)
1515 		panic("vdrop: holdcnt");
1516 	vp->v_holdcnt--;
1517 	if (VSHOULDFREE(vp))
1518 		vfree(vp);
1519 	splx(s);
1520 }
1521 
1522 /*
1523  * Remove any vnodes in the vnode table belonging to mount point mp.
1524  *
1525  * If MNT_NOFORCE is specified, there should not be any active ones,
1526  * return error if any are found (nb: this is a user error, not a
1527  * system error). If MNT_FORCE is specified, detach any active vnodes
1528  * that are found.
1529  */
1530 #ifdef DIAGNOSTIC
1531 static int busyprt = 0;		/* print out busy vnodes */
1532 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
1533 #endif
1534 
1535 int
1536 vflush(mp, skipvp, flags)
1537 	struct mount *mp;
1538 	struct vnode *skipvp;
1539 	int flags;
1540 {
1541 	struct proc *p = curproc;	/* XXX */
1542 	struct vnode *vp, *nvp;
1543 	int busy = 0;
1544 
1545 	simple_lock(&mntvnode_slock);
1546 loop:
1547 	for (vp = mp->mnt_vnodelist.lh_first; vp; vp = nvp) {
1548 		/*
1549 		 * Make sure this vnode wasn't reclaimed in getnewvnode().
1550 		 * Start over if it has (it won't be on the list anymore).
1551 		 */
1552 		if (vp->v_mount != mp)
1553 			goto loop;
1554 		nvp = vp->v_mntvnodes.le_next;
1555 		/*
1556 		 * Skip over a selected vnode.
1557 		 */
1558 		if (vp == skipvp)
1559 			continue;
1560 
1561 		simple_lock(&vp->v_interlock);
1562 		/*
1563 		 * Skip over a vnodes marked VSYSTEM.
1564 		 */
1565 		if ((flags & SKIPSYSTEM) && (vp->v_flag & VSYSTEM)) {
1566 			simple_unlock(&vp->v_interlock);
1567 			continue;
1568 		}
1569 		/*
1570 		 * If WRITECLOSE is set, only flush out regular file vnodes
1571 		 * open for writing.
1572 		 */
1573 		if ((flags & WRITECLOSE) &&
1574 		    (vp->v_writecount == 0 || vp->v_type != VREG)) {
1575 			simple_unlock(&vp->v_interlock);
1576 			continue;
1577 		}
1578 
1579 		/*
1580 		 * With v_usecount == 0, all we need to do is clear out the
1581 		 * vnode data structures and we are done.
1582 		 */
1583 		if (vp->v_usecount == 0) {
1584 			simple_unlock(&mntvnode_slock);
1585 			vgonel(vp, p);
1586 			simple_lock(&mntvnode_slock);
1587 			continue;
1588 		}
1589 
1590 		/*
1591 		 * If FORCECLOSE is set, forcibly close the vnode. For block
1592 		 * or character devices, revert to an anonymous device. For
1593 		 * all other files, just kill them.
1594 		 */
1595 		if (flags & FORCECLOSE) {
1596 			simple_unlock(&mntvnode_slock);
1597 			if (vp->v_type != VBLK && vp->v_type != VCHR) {
1598 				vgonel(vp, p);
1599 			} else {
1600 				vclean(vp, 0, p);
1601 				vp->v_op = spec_vnodeop_p;
1602 				insmntque(vp, (struct mount *) 0);
1603 			}
1604 			simple_lock(&mntvnode_slock);
1605 			continue;
1606 		}
1607 #ifdef DIAGNOSTIC
1608 		if (busyprt)
1609 			vprint("vflush: busy vnode", vp);
1610 #endif
1611 		simple_unlock(&vp->v_interlock);
1612 		busy++;
1613 	}
1614 	simple_unlock(&mntvnode_slock);
1615 	if (busy)
1616 		return (EBUSY);
1617 	return (0);
1618 }
1619 
1620 /*
1621  * Disassociate the underlying file system from a vnode.
1622  */
1623 static void
1624 vclean(vp, flags, p)
1625 	struct vnode *vp;
1626 	int flags;
1627 	struct proc *p;
1628 {
1629 	int active;
1630 	vm_object_t obj;
1631 
1632 	/*
1633 	 * Check to see if the vnode is in use. If so we have to reference it
1634 	 * before we clean it out so that its count cannot fall to zero and
1635 	 * generate a race against ourselves to recycle it.
1636 	 */
1637 	if ((active = vp->v_usecount))
1638 		vp->v_usecount++;
1639 
1640 	/*
1641 	 * Prevent the vnode from being recycled or brought into use while we
1642 	 * clean it out.
1643 	 */
1644 	if (vp->v_flag & VXLOCK)
1645 		panic("vclean: deadlock");
1646 	vp->v_flag |= VXLOCK;
1647 	/*
1648 	 * Even if the count is zero, the VOP_INACTIVE routine may still
1649 	 * have the object locked while it cleans it out. The VOP_LOCK
1650 	 * ensures that the VOP_INACTIVE routine is done with its work.
1651 	 * For active vnodes, it ensures that no other activity can
1652 	 * occur while the underlying object is being cleaned out.
1653 	 */
1654 	VOP_LOCK(vp, LK_DRAIN | LK_INTERLOCK, p);
1655 
1656 	/*
1657 	 * Clean out any buffers associated with the vnode.
1658 	 */
1659 	vinvalbuf(vp, V_SAVE, NOCRED, p, 0, 0);
1660 	if ((obj = vp->v_object) != NULL) {
1661 		if (obj->ref_count == 0) {
1662 			/*
1663 			 * vclean() may be called twice.  The first time removes the
1664 			 * primary reference to the object, the second time goes
1665 			 * one further and is a special-case to terminate the object.
1666 			 */
1667 			vm_object_terminate(obj);
1668 		} else {
1669 			/*
1670 			 * Woe to the process that tries to page now :-).
1671 			 */
1672 			vm_pager_deallocate(obj);
1673 		}
1674 	}
1675 
1676 	/*
1677 	 * If purging an active vnode, it must be closed and
1678 	 * deactivated before being reclaimed. Note that the
1679 	 * VOP_INACTIVE will unlock the vnode.
1680 	 */
1681 	if (active) {
1682 		if (flags & DOCLOSE)
1683 			VOP_CLOSE(vp, FNONBLOCK, NOCRED, p);
1684 		VOP_INACTIVE(vp, p);
1685 	} else {
1686 		/*
1687 		 * Any other processes trying to obtain this lock must first
1688 		 * wait for VXLOCK to clear, then call the new lock operation.
1689 		 */
1690 		VOP_UNLOCK(vp, 0, p);
1691 	}
1692 	/*
1693 	 * Reclaim the vnode.
1694 	 */
1695 	if (VOP_RECLAIM(vp, p))
1696 		panic("vclean: cannot reclaim");
1697 
1698 	if (active)
1699 		vrele(vp);
1700 
1701 	cache_purge(vp);
1702 	if (vp->v_vnlock) {
1703 		FREE(vp->v_vnlock, M_VNODE);
1704 		vp->v_vnlock = NULL;
1705 	}
1706 
1707 	if (VSHOULDFREE(vp))
1708 		vfree(vp);
1709 
1710 	/*
1711 	 * Done with purge, notify sleepers of the grim news.
1712 	 */
1713 	vp->v_op = dead_vnodeop_p;
1714 	vn_pollgone(vp);
1715 	vp->v_tag = VT_NON;
1716 	vp->v_flag &= ~VXLOCK;
1717 	if (vp->v_flag & VXWANT) {
1718 		vp->v_flag &= ~VXWANT;
1719 		wakeup((caddr_t) vp);
1720 	}
1721 }
1722 
1723 /*
1724  * Eliminate all activity associated with the requested vnode
1725  * and with all vnodes aliased to the requested vnode.
1726  */
1727 int
1728 vop_revoke(ap)
1729 	struct vop_revoke_args /* {
1730 		struct vnode *a_vp;
1731 		int a_flags;
1732 	} */ *ap;
1733 {
1734 	struct vnode *vp, *vq;
1735 	dev_t dev;
1736 
1737 	KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
1738 
1739 	vp = ap->a_vp;
1740 	/*
1741 	 * If a vgone (or vclean) is already in progress,
1742 	 * wait until it is done and return.
1743 	 */
1744 	if (vp->v_flag & VXLOCK) {
1745 		vp->v_flag |= VXWANT;
1746 		simple_unlock(&vp->v_interlock);
1747 		tsleep((caddr_t)vp, PINOD, "vop_revokeall", 0);
1748 		return (0);
1749 	}
1750 	dev = vp->v_rdev;
1751 	for (;;) {
1752 		simple_lock(&spechash_slock);
1753 		vq = SLIST_FIRST(&dev->si_hlist);
1754 		simple_unlock(&spechash_slock);
1755 		if (!vq)
1756 			break;
1757 		vgone(vq);
1758 	}
1759 	return (0);
1760 }
1761 
1762 /*
1763  * Recycle an unused vnode to the front of the free list.
1764  * Release the passed interlock if the vnode will be recycled.
1765  */
1766 int
1767 vrecycle(vp, inter_lkp, p)
1768 	struct vnode *vp;
1769 	struct simplelock *inter_lkp;
1770 	struct proc *p;
1771 {
1772 
1773 	simple_lock(&vp->v_interlock);
1774 	if (vp->v_usecount == 0) {
1775 		if (inter_lkp) {
1776 			simple_unlock(inter_lkp);
1777 		}
1778 		vgonel(vp, p);
1779 		return (1);
1780 	}
1781 	simple_unlock(&vp->v_interlock);
1782 	return (0);
1783 }
1784 
1785 /*
1786  * Eliminate all activity associated with a vnode
1787  * in preparation for reuse.
1788  */
1789 void
1790 vgone(vp)
1791 	register struct vnode *vp;
1792 {
1793 	struct proc *p = curproc;	/* XXX */
1794 
1795 	simple_lock(&vp->v_interlock);
1796 	vgonel(vp, p);
1797 }
1798 
1799 /*
1800  * vgone, with the vp interlock held.
1801  */
1802 static void
1803 vgonel(vp, p)
1804 	struct vnode *vp;
1805 	struct proc *p;
1806 {
1807 	int s;
1808 
1809 	/*
1810 	 * If a vgone (or vclean) is already in progress,
1811 	 * wait until it is done and return.
1812 	 */
1813 	if (vp->v_flag & VXLOCK) {
1814 		vp->v_flag |= VXWANT;
1815 		simple_unlock(&vp->v_interlock);
1816 		tsleep((caddr_t)vp, PINOD, "vgone", 0);
1817 		return;
1818 	}
1819 
1820 	/*
1821 	 * Clean out the filesystem specific data.
1822 	 */
1823 	vclean(vp, DOCLOSE, p);
1824 	simple_lock(&vp->v_interlock);
1825 
1826 	/*
1827 	 * Delete from old mount point vnode list, if on one.
1828 	 */
1829 	if (vp->v_mount != NULL)
1830 		insmntque(vp, (struct mount *)0);
1831 	/*
1832 	 * If special device, remove it from special device alias list
1833 	 * if it is on one.
1834 	 */
1835 	if ((vp->v_type == VBLK || vp->v_type == VCHR) && vp->v_rdev != NULL) {
1836 		simple_lock(&spechash_slock);
1837 		SLIST_REMOVE(&vp->v_hashchain, vp, vnode, v_specnext);
1838 		freedev(vp->v_rdev);
1839 		simple_unlock(&spechash_slock);
1840 		vp->v_rdev = NULL;
1841 	}
1842 
1843 	/*
1844 	 * If it is on the freelist and not already at the head,
1845 	 * move it to the head of the list. The test of the back
1846 	 * pointer and the reference count of zero is because
1847 	 * it will be removed from the free list by getnewvnode,
1848 	 * but will not have its reference count incremented until
1849 	 * after calling vgone. If the reference count were
1850 	 * incremented first, vgone would (incorrectly) try to
1851 	 * close the previous instance of the underlying object.
1852 	 */
1853 	if (vp->v_usecount == 0 && !(vp->v_flag & VDOOMED)) {
1854 		s = splbio();
1855 		simple_lock(&vnode_free_list_slock);
1856 		if (vp->v_flag & VFREE) {
1857 			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
1858 		} else if (vp->v_flag & VTBFREE) {
1859 			TAILQ_REMOVE(&vnode_tobefree_list, vp, v_freelist);
1860 			vp->v_flag &= ~VTBFREE;
1861 			freevnodes++;
1862 		} else
1863 			freevnodes++;
1864 		vp->v_flag |= VFREE;
1865 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
1866 		simple_unlock(&vnode_free_list_slock);
1867 		splx(s);
1868 	}
1869 
1870 	vp->v_type = VBAD;
1871 	simple_unlock(&vp->v_interlock);
1872 }
1873 
1874 /*
1875  * Lookup a vnode by device number.
1876  */
1877 int
1878 vfinddev(dev, type, vpp)
1879 	dev_t dev;
1880 	enum vtype type;
1881 	struct vnode **vpp;
1882 {
1883 	struct vnode *vp;
1884 
1885 	simple_lock(&spechash_slock);
1886 	SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
1887 		if (type == vp->v_type) {
1888 			*vpp = vp;
1889 			simple_unlock(&spechash_slock);
1890 			return (1);
1891 		}
1892 	}
1893 	simple_unlock(&spechash_slock);
1894 	return (0);
1895 }
1896 
1897 /*
1898  * Calculate the total number of references to a special device.
1899  */
1900 int
1901 vcount(vp)
1902 	struct vnode *vp;
1903 {
1904 	struct vnode *vq;
1905 	int count;
1906 
1907 	count = 0;
1908 	simple_lock(&spechash_slock);
1909 	SLIST_FOREACH(vq, &vp->v_hashchain, v_specnext)
1910 		count += vq->v_usecount;
1911 	simple_unlock(&spechash_slock);
1912 	return (count);
1913 }
1914 
1915 /*
1916  * Print out a description of a vnode.
1917  */
1918 static char *typename[] =
1919 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
1920 
1921 void
1922 vprint(label, vp)
1923 	char *label;
1924 	struct vnode *vp;
1925 {
1926 	char buf[96];
1927 
1928 	if (label != NULL)
1929 		printf("%s: %p: ", label, (void *)vp);
1930 	else
1931 		printf("%p: ", (void *)vp);
1932 	printf("type %s, usecount %d, writecount %d, refcount %d,",
1933 	    typename[vp->v_type], vp->v_usecount, vp->v_writecount,
1934 	    vp->v_holdcnt);
1935 	buf[0] = '\0';
1936 	if (vp->v_flag & VROOT)
1937 		strcat(buf, "|VROOT");
1938 	if (vp->v_flag & VTEXT)
1939 		strcat(buf, "|VTEXT");
1940 	if (vp->v_flag & VSYSTEM)
1941 		strcat(buf, "|VSYSTEM");
1942 	if (vp->v_flag & VXLOCK)
1943 		strcat(buf, "|VXLOCK");
1944 	if (vp->v_flag & VXWANT)
1945 		strcat(buf, "|VXWANT");
1946 	if (vp->v_flag & VBWAIT)
1947 		strcat(buf, "|VBWAIT");
1948 	if (vp->v_flag & VDOOMED)
1949 		strcat(buf, "|VDOOMED");
1950 	if (vp->v_flag & VFREE)
1951 		strcat(buf, "|VFREE");
1952 	if (vp->v_flag & VOBJBUF)
1953 		strcat(buf, "|VOBJBUF");
1954 	if (buf[0] != '\0')
1955 		printf(" flags (%s)", &buf[1]);
1956 	if (vp->v_data == NULL) {
1957 		printf("\n");
1958 	} else {
1959 		printf("\n\t");
1960 		VOP_PRINT(vp);
1961 	}
1962 }
1963 
1964 #ifdef DDB
1965 #include <ddb/ddb.h>
1966 /*
1967  * List all of the locked vnodes in the system.
1968  * Called when debugging the kernel.
1969  */
1970 DB_SHOW_COMMAND(lockedvnodes, lockedvnodes)
1971 {
1972 	struct proc *p = curproc;	/* XXX */
1973 	struct mount *mp, *nmp;
1974 	struct vnode *vp;
1975 
1976 	printf("Locked vnodes\n");
1977 	simple_lock(&mountlist_slock);
1978 	for (mp = mountlist.cqh_first; mp != (void *)&mountlist; mp = nmp) {
1979 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_slock, p)) {
1980 			nmp = mp->mnt_list.cqe_next;
1981 			continue;
1982 		}
1983 		for (vp = mp->mnt_vnodelist.lh_first;
1984 		     vp != NULL;
1985 		     vp = vp->v_mntvnodes.le_next) {
1986 			if (VOP_ISLOCKED(vp))
1987 				vprint((char *)0, vp);
1988 		}
1989 		simple_lock(&mountlist_slock);
1990 		nmp = mp->mnt_list.cqe_next;
1991 		vfs_unbusy(mp, p);
1992 	}
1993 	simple_unlock(&mountlist_slock);
1994 }
1995 #endif
1996 
1997 /*
1998  * Top level filesystem related information gathering.
1999  */
2000 static int	sysctl_ovfs_conf __P(SYSCTL_HANDLER_ARGS);
2001 
2002 static int
2003 vfs_sysctl SYSCTL_HANDLER_ARGS
2004 {
2005 	int *name = (int *)arg1 - 1;	/* XXX */
2006 	u_int namelen = arg2 + 1;	/* XXX */
2007 	struct vfsconf *vfsp;
2008 
2009 #if 1 || defined(COMPAT_PRELITE2)
2010 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2011 	if (namelen == 1)
2012 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2013 #endif
2014 
2015 #ifdef notyet
2016 	/* all sysctl names at this level are at least name and field */
2017 	if (namelen < 2)
2018 		return (ENOTDIR);		/* overloaded */
2019 	if (name[0] != VFS_GENERIC) {
2020 		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2021 			if (vfsp->vfc_typenum == name[0])
2022 				break;
2023 		if (vfsp == NULL)
2024 			return (EOPNOTSUPP);
2025 		return ((*vfsp->vfc_vfsops->vfs_sysctl)(&name[1], namelen - 1,
2026 		    oldp, oldlenp, newp, newlen, p));
2027 	}
2028 #endif
2029 	switch (name[1]) {
2030 	case VFS_MAXTYPENUM:
2031 		if (namelen != 2)
2032 			return (ENOTDIR);
2033 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2034 	case VFS_CONF:
2035 		if (namelen != 3)
2036 			return (ENOTDIR);	/* overloaded */
2037 		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2038 			if (vfsp->vfc_typenum == name[2])
2039 				break;
2040 		if (vfsp == NULL)
2041 			return (EOPNOTSUPP);
2042 		return (SYSCTL_OUT(req, vfsp, sizeof *vfsp));
2043 	}
2044 	return (EOPNOTSUPP);
2045 }
2046 
2047 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD, vfs_sysctl,
2048 	"Generic filesystem");
2049 
2050 #if 1 || defined(COMPAT_PRELITE2)
2051 
2052 static int
2053 sysctl_ovfs_conf SYSCTL_HANDLER_ARGS
2054 {
2055 	int error;
2056 	struct vfsconf *vfsp;
2057 	struct ovfsconf ovfs;
2058 
2059 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
2060 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2061 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2062 		ovfs.vfc_index = vfsp->vfc_typenum;
2063 		ovfs.vfc_refcount = vfsp->vfc_refcount;
2064 		ovfs.vfc_flags = vfsp->vfc_flags;
2065 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2066 		if (error)
2067 			return error;
2068 	}
2069 	return 0;
2070 }
2071 
2072 #endif /* 1 || COMPAT_PRELITE2 */
2073 
2074 #if 0
2075 #define KINFO_VNODESLOP	10
2076 /*
2077  * Dump vnode list (via sysctl).
2078  * Copyout address of vnode followed by vnode.
2079  */
2080 /* ARGSUSED */
2081 static int
2082 sysctl_vnode SYSCTL_HANDLER_ARGS
2083 {
2084 	struct proc *p = curproc;	/* XXX */
2085 	struct mount *mp, *nmp;
2086 	struct vnode *nvp, *vp;
2087 	int error;
2088 
2089 #define VPTRSZ	sizeof (struct vnode *)
2090 #define VNODESZ	sizeof (struct vnode)
2091 
2092 	req->lock = 0;
2093 	if (!req->oldptr) /* Make an estimate */
2094 		return (SYSCTL_OUT(req, 0,
2095 			(numvnodes + KINFO_VNODESLOP) * (VPTRSZ + VNODESZ)));
2096 
2097 	simple_lock(&mountlist_slock);
2098 	for (mp = mountlist.cqh_first; mp != (void *)&mountlist; mp = nmp) {
2099 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_slock, p)) {
2100 			nmp = mp->mnt_list.cqe_next;
2101 			continue;
2102 		}
2103 again:
2104 		simple_lock(&mntvnode_slock);
2105 		for (vp = mp->mnt_vnodelist.lh_first;
2106 		     vp != NULL;
2107 		     vp = nvp) {
2108 			/*
2109 			 * Check that the vp is still associated with
2110 			 * this filesystem.  RACE: could have been
2111 			 * recycled onto the same filesystem.
2112 			 */
2113 			if (vp->v_mount != mp) {
2114 				simple_unlock(&mntvnode_slock);
2115 				goto again;
2116 			}
2117 			nvp = vp->v_mntvnodes.le_next;
2118 			simple_unlock(&mntvnode_slock);
2119 			if ((error = SYSCTL_OUT(req, &vp, VPTRSZ)) ||
2120 			    (error = SYSCTL_OUT(req, vp, VNODESZ)))
2121 				return (error);
2122 			simple_lock(&mntvnode_slock);
2123 		}
2124 		simple_unlock(&mntvnode_slock);
2125 		simple_lock(&mountlist_slock);
2126 		nmp = mp->mnt_list.cqe_next;
2127 		vfs_unbusy(mp, p);
2128 	}
2129 	simple_unlock(&mountlist_slock);
2130 
2131 	return (0);
2132 }
2133 #endif
2134 
2135 /*
2136  * XXX
2137  * Exporting the vnode list on large systems causes them to crash.
2138  * Exporting the vnode list on medium systems causes sysctl to coredump.
2139  */
2140 #if 0
2141 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
2142 	0, 0, sysctl_vnode, "S,vnode", "");
2143 #endif
2144 
2145 /*
2146  * Check to see if a filesystem is mounted on a block device.
2147  */
2148 int
2149 vfs_mountedon(vp)
2150 	struct vnode *vp;
2151 {
2152 
2153 	if (vp->v_specmountpoint != NULL)
2154 		return (EBUSY);
2155 	return (0);
2156 }
2157 
2158 /*
2159  * Unmount all filesystems. The list is traversed in reverse order
2160  * of mounting to avoid dependencies.
2161  */
2162 void
2163 vfs_unmountall()
2164 {
2165 	struct mount *mp, *nmp;
2166 	struct proc *p;
2167 	int error;
2168 
2169 	if (curproc != NULL)
2170 		p = curproc;
2171 	else
2172 		p = initproc;	/* XXX XXX should this be proc0? */
2173 	/*
2174 	 * Since this only runs when rebooting, it is not interlocked.
2175 	 */
2176 	for (mp = mountlist.cqh_last; mp != (void *)&mountlist; mp = nmp) {
2177 		nmp = mp->mnt_list.cqe_prev;
2178 		error = dounmount(mp, MNT_FORCE, p);
2179 		if (error) {
2180 			printf("unmount of %s failed (",
2181 			    mp->mnt_stat.f_mntonname);
2182 			if (error == EBUSY)
2183 				printf("BUSY)\n");
2184 			else
2185 				printf("%d)\n", error);
2186 		}
2187 	}
2188 }
2189 
2190 /*
2191  * Build hash lists of net addresses and hang them off the mount point.
2192  * Called by ufs_mount() to set up the lists of export addresses.
2193  */
2194 static int
2195 vfs_hang_addrlist(mp, nep, argp)
2196 	struct mount *mp;
2197 	struct netexport *nep;
2198 	struct export_args *argp;
2199 {
2200 	register struct netcred *np;
2201 	register struct radix_node_head *rnh;
2202 	register int i;
2203 	struct radix_node *rn;
2204 	struct sockaddr *saddr, *smask = 0;
2205 	struct domain *dom;
2206 	int error;
2207 
2208 	if (argp->ex_addrlen == 0) {
2209 		if (mp->mnt_flag & MNT_DEFEXPORTED)
2210 			return (EPERM);
2211 		np = &nep->ne_defexported;
2212 		np->netc_exflags = argp->ex_flags;
2213 		np->netc_anon = argp->ex_anon;
2214 		np->netc_anon.cr_ref = 1;
2215 		mp->mnt_flag |= MNT_DEFEXPORTED;
2216 		return (0);
2217 	}
2218 	i = sizeof(struct netcred) + argp->ex_addrlen + argp->ex_masklen;
2219 	np = (struct netcred *) malloc(i, M_NETADDR, M_WAITOK);
2220 	bzero((caddr_t) np, i);
2221 	saddr = (struct sockaddr *) (np + 1);
2222 	if ((error = copyin(argp->ex_addr, (caddr_t) saddr, argp->ex_addrlen)))
2223 		goto out;
2224 	if (saddr->sa_len > argp->ex_addrlen)
2225 		saddr->sa_len = argp->ex_addrlen;
2226 	if (argp->ex_masklen) {
2227 		smask = (struct sockaddr *) ((caddr_t) saddr + argp->ex_addrlen);
2228 		error = copyin(argp->ex_mask, (caddr_t) smask, argp->ex_masklen);
2229 		if (error)
2230 			goto out;
2231 		if (smask->sa_len > argp->ex_masklen)
2232 			smask->sa_len = argp->ex_masklen;
2233 	}
2234 	i = saddr->sa_family;
2235 	if ((rnh = nep->ne_rtable[i]) == 0) {
2236 		/*
2237 		 * Seems silly to initialize every AF when most are not used,
2238 		 * do so on demand here
2239 		 */
2240 		for (dom = domains; dom; dom = dom->dom_next)
2241 			if (dom->dom_family == i && dom->dom_rtattach) {
2242 				dom->dom_rtattach((void **) &nep->ne_rtable[i],
2243 				    dom->dom_rtoffset);
2244 				break;
2245 			}
2246 		if ((rnh = nep->ne_rtable[i]) == 0) {
2247 			error = ENOBUFS;
2248 			goto out;
2249 		}
2250 	}
2251 	rn = (*rnh->rnh_addaddr) ((caddr_t) saddr, (caddr_t) smask, rnh,
2252 	    np->netc_rnodes);
2253 	if (rn == 0 || np != (struct netcred *) rn) {	/* already exists */
2254 		error = EPERM;
2255 		goto out;
2256 	}
2257 	np->netc_exflags = argp->ex_flags;
2258 	np->netc_anon = argp->ex_anon;
2259 	np->netc_anon.cr_ref = 1;
2260 	return (0);
2261 out:
2262 	free(np, M_NETADDR);
2263 	return (error);
2264 }
2265 
2266 /* ARGSUSED */
2267 static int
2268 vfs_free_netcred(rn, w)
2269 	struct radix_node *rn;
2270 	void *w;
2271 {
2272 	register struct radix_node_head *rnh = (struct radix_node_head *) w;
2273 
2274 	(*rnh->rnh_deladdr) (rn->rn_key, rn->rn_mask, rnh);
2275 	free((caddr_t) rn, M_NETADDR);
2276 	return (0);
2277 }
2278 
2279 /*
2280  * Free the net address hash lists that are hanging off the mount points.
2281  */
2282 static void
2283 vfs_free_addrlist(nep)
2284 	struct netexport *nep;
2285 {
2286 	register int i;
2287 	register struct radix_node_head *rnh;
2288 
2289 	for (i = 0; i <= AF_MAX; i++)
2290 		if ((rnh = nep->ne_rtable[i])) {
2291 			(*rnh->rnh_walktree) (rnh, vfs_free_netcred,
2292 			    (caddr_t) rnh);
2293 			free((caddr_t) rnh, M_RTABLE);
2294 			nep->ne_rtable[i] = 0;
2295 		}
2296 }
2297 
2298 int
2299 vfs_export(mp, nep, argp)
2300 	struct mount *mp;
2301 	struct netexport *nep;
2302 	struct export_args *argp;
2303 {
2304 	int error;
2305 
2306 	if (argp->ex_flags & MNT_DELEXPORT) {
2307 		if (mp->mnt_flag & MNT_EXPUBLIC) {
2308 			vfs_setpublicfs(NULL, NULL, NULL);
2309 			mp->mnt_flag &= ~MNT_EXPUBLIC;
2310 		}
2311 		vfs_free_addrlist(nep);
2312 		mp->mnt_flag &= ~(MNT_EXPORTED | MNT_DEFEXPORTED);
2313 	}
2314 	if (argp->ex_flags & MNT_EXPORTED) {
2315 		if (argp->ex_flags & MNT_EXPUBLIC) {
2316 			if ((error = vfs_setpublicfs(mp, nep, argp)) != 0)
2317 				return (error);
2318 			mp->mnt_flag |= MNT_EXPUBLIC;
2319 		}
2320 		if ((error = vfs_hang_addrlist(mp, nep, argp)))
2321 			return (error);
2322 		mp->mnt_flag |= MNT_EXPORTED;
2323 	}
2324 	return (0);
2325 }
2326 
2327 
2328 /*
2329  * Set the publicly exported filesystem (WebNFS). Currently, only
2330  * one public filesystem is possible in the spec (RFC 2054 and 2055)
2331  */
2332 int
2333 vfs_setpublicfs(mp, nep, argp)
2334 	struct mount *mp;
2335 	struct netexport *nep;
2336 	struct export_args *argp;
2337 {
2338 	int error;
2339 	struct vnode *rvp;
2340 	char *cp;
2341 
2342 	/*
2343 	 * mp == NULL -> invalidate the current info, the FS is
2344 	 * no longer exported. May be called from either vfs_export
2345 	 * or unmount, so check if it hasn't already been done.
2346 	 */
2347 	if (mp == NULL) {
2348 		if (nfs_pub.np_valid) {
2349 			nfs_pub.np_valid = 0;
2350 			if (nfs_pub.np_index != NULL) {
2351 				FREE(nfs_pub.np_index, M_TEMP);
2352 				nfs_pub.np_index = NULL;
2353 			}
2354 		}
2355 		return (0);
2356 	}
2357 
2358 	/*
2359 	 * Only one allowed at a time.
2360 	 */
2361 	if (nfs_pub.np_valid != 0 && mp != nfs_pub.np_mount)
2362 		return (EBUSY);
2363 
2364 	/*
2365 	 * Get real filehandle for root of exported FS.
2366 	 */
2367 	bzero((caddr_t)&nfs_pub.np_handle, sizeof(nfs_pub.np_handle));
2368 	nfs_pub.np_handle.fh_fsid = mp->mnt_stat.f_fsid;
2369 
2370 	if ((error = VFS_ROOT(mp, &rvp)))
2371 		return (error);
2372 
2373 	if ((error = VFS_VPTOFH(rvp, &nfs_pub.np_handle.fh_fid)))
2374 		return (error);
2375 
2376 	vput(rvp);
2377 
2378 	/*
2379 	 * If an indexfile was specified, pull it in.
2380 	 */
2381 	if (argp->ex_indexfile != NULL) {
2382 		MALLOC(nfs_pub.np_index, char *, MAXNAMLEN + 1, M_TEMP,
2383 		    M_WAITOK);
2384 		error = copyinstr(argp->ex_indexfile, nfs_pub.np_index,
2385 		    MAXNAMLEN, (size_t *)0);
2386 		if (!error) {
2387 			/*
2388 			 * Check for illegal filenames.
2389 			 */
2390 			for (cp = nfs_pub.np_index; *cp; cp++) {
2391 				if (*cp == '/') {
2392 					error = EINVAL;
2393 					break;
2394 				}
2395 			}
2396 		}
2397 		if (error) {
2398 			FREE(nfs_pub.np_index, M_TEMP);
2399 			return (error);
2400 		}
2401 	}
2402 
2403 	nfs_pub.np_mount = mp;
2404 	nfs_pub.np_valid = 1;
2405 	return (0);
2406 }
2407 
2408 struct netcred *
2409 vfs_export_lookup(mp, nep, nam)
2410 	register struct mount *mp;
2411 	struct netexport *nep;
2412 	struct sockaddr *nam;
2413 {
2414 	register struct netcred *np;
2415 	register struct radix_node_head *rnh;
2416 	struct sockaddr *saddr;
2417 
2418 	np = NULL;
2419 	if (mp->mnt_flag & MNT_EXPORTED) {
2420 		/*
2421 		 * Lookup in the export list first.
2422 		 */
2423 		if (nam != NULL) {
2424 			saddr = nam;
2425 			rnh = nep->ne_rtable[saddr->sa_family];
2426 			if (rnh != NULL) {
2427 				np = (struct netcred *)
2428 					(*rnh->rnh_matchaddr)((caddr_t)saddr,
2429 							      rnh);
2430 				if (np && np->netc_rnodes->rn_flags & RNF_ROOT)
2431 					np = NULL;
2432 			}
2433 		}
2434 		/*
2435 		 * If no address match, use the default if it exists.
2436 		 */
2437 		if (np == NULL && mp->mnt_flag & MNT_DEFEXPORTED)
2438 			np = &nep->ne_defexported;
2439 	}
2440 	return (np);
2441 }
2442 
2443 /*
2444  * perform msync on all vnodes under a mount point
2445  * the mount point must be locked.
2446  */
2447 void
2448 vfs_msync(struct mount *mp, int flags) {
2449 	struct vnode *vp, *nvp;
2450 	struct vm_object *obj;
2451 	int anyio, tries;
2452 
2453 	tries = 5;
2454 loop:
2455 	anyio = 0;
2456 	for (vp = mp->mnt_vnodelist.lh_first; vp != NULL; vp = nvp) {
2457 
2458 		nvp = vp->v_mntvnodes.le_next;
2459 
2460 		if (vp->v_mount != mp) {
2461 			goto loop;
2462 		}
2463 
2464 		if (vp->v_flag & VXLOCK)	/* XXX: what if MNT_WAIT? */
2465 			continue;
2466 
2467 		if (flags != MNT_WAIT) {
2468 			obj = vp->v_object;
2469 			if (obj == NULL || (obj->flags & OBJ_MIGHTBEDIRTY) == 0)
2470 				continue;
2471 			if (VOP_ISLOCKED(vp))
2472 				continue;
2473 		}
2474 
2475 		simple_lock(&vp->v_interlock);
2476 		if (vp->v_object &&
2477 		   (vp->v_object->flags & OBJ_MIGHTBEDIRTY)) {
2478 			if (!vget(vp,
2479 				LK_INTERLOCK | LK_EXCLUSIVE | LK_RETRY | LK_NOOBJ, curproc)) {
2480 				if (vp->v_object) {
2481 					vm_object_page_clean(vp->v_object, 0, 0, flags == MNT_WAIT ? OBJPC_SYNC : 0);
2482 					anyio = 1;
2483 				}
2484 				vput(vp);
2485 			}
2486 		} else {
2487 			simple_unlock(&vp->v_interlock);
2488 		}
2489 	}
2490 	if (anyio && (--tries > 0))
2491 		goto loop;
2492 }
2493 
2494 /*
2495  * Create the VM object needed for VMIO and mmap support.  This
2496  * is done for all VREG files in the system.  Some filesystems might
2497  * afford the additional metadata buffering capability of the
2498  * VMIO code by making the device node be VMIO mode also.
2499  *
2500  * vp must be locked when vfs_object_create is called.
2501  */
2502 int
2503 vfs_object_create(vp, p, cred)
2504 	struct vnode *vp;
2505 	struct proc *p;
2506 	struct ucred *cred;
2507 {
2508 	struct vattr vat;
2509 	vm_object_t object;
2510 	int error = 0;
2511 
2512 	if (vp->v_type != VBLK && vn_canvmio(vp) == FALSE)
2513 		return 0;
2514 
2515 retry:
2516 	if ((object = vp->v_object) == NULL) {
2517 		if (vp->v_type == VREG || vp->v_type == VDIR) {
2518 			if ((error = VOP_GETATTR(vp, &vat, cred, p)) != 0)
2519 				goto retn;
2520 			object = vnode_pager_alloc(vp, vat.va_size, 0, 0);
2521 		} else if (devsw(vp->v_rdev) != NULL) {
2522 			/*
2523 			 * This simply allocates the biggest object possible
2524 			 * for a VBLK vnode.  This should be fixed, but doesn't
2525 			 * cause any problems (yet).
2526 			 */
2527 			object = vnode_pager_alloc(vp, IDX_TO_OFF(INT_MAX), 0, 0);
2528 		} else {
2529 			goto retn;
2530 		}
2531 		/*
2532 		 * Dereference the reference we just created.  This assumes
2533 		 * that the object is associated with the vp.
2534 		 */
2535 		object->ref_count--;
2536 		vp->v_usecount--;
2537 	} else {
2538 		if (object->flags & OBJ_DEAD) {
2539 			VOP_UNLOCK(vp, 0, p);
2540 			tsleep(object, PVM, "vodead", 0);
2541 			vn_lock(vp, LK_EXCLUSIVE | LK_RETRY, p);
2542 			goto retry;
2543 		}
2544 	}
2545 
2546 	KASSERT(vp->v_object != NULL, ("vfs_object_create: NULL object"));
2547 	vp->v_flag |= VOBJBUF;
2548 
2549 retn:
2550 	return error;
2551 }
2552 
2553 static void
2554 vfree(vp)
2555 	struct vnode *vp;
2556 {
2557 	int s;
2558 
2559 	s = splbio();
2560 	simple_lock(&vnode_free_list_slock);
2561 	if (vp->v_flag & VTBFREE) {
2562 		TAILQ_REMOVE(&vnode_tobefree_list, vp, v_freelist);
2563 		vp->v_flag &= ~VTBFREE;
2564 	}
2565 	if (vp->v_flag & VAGE) {
2566 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2567 	} else {
2568 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
2569 	}
2570 	freevnodes++;
2571 	simple_unlock(&vnode_free_list_slock);
2572 	vp->v_flag &= ~VAGE;
2573 	vp->v_flag |= VFREE;
2574 	splx(s);
2575 }
2576 
2577 void
2578 vbusy(vp)
2579 	struct vnode *vp;
2580 {
2581 	int s;
2582 
2583 	s = splbio();
2584 	simple_lock(&vnode_free_list_slock);
2585 	if (vp->v_flag & VTBFREE) {
2586 		TAILQ_REMOVE(&vnode_tobefree_list, vp, v_freelist);
2587 		vp->v_flag &= ~VTBFREE;
2588 	} else {
2589 		TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2590 		freevnodes--;
2591 	}
2592 	simple_unlock(&vnode_free_list_slock);
2593 	vp->v_flag &= ~(VFREE|VAGE);
2594 	splx(s);
2595 }
2596 
2597 /*
2598  * Record a process's interest in events which might happen to
2599  * a vnode.  Because poll uses the historic select-style interface
2600  * internally, this routine serves as both the ``check for any
2601  * pending events'' and the ``record my interest in future events''
2602  * functions.  (These are done together, while the lock is held,
2603  * to avoid race conditions.)
2604  */
2605 int
2606 vn_pollrecord(vp, p, events)
2607 	struct vnode *vp;
2608 	struct proc *p;
2609 	short events;
2610 {
2611 	simple_lock(&vp->v_pollinfo.vpi_lock);
2612 	if (vp->v_pollinfo.vpi_revents & events) {
2613 		/*
2614 		 * This leaves events we are not interested
2615 		 * in available for the other process which
2616 		 * which presumably had requested them
2617 		 * (otherwise they would never have been
2618 		 * recorded).
2619 		 */
2620 		events &= vp->v_pollinfo.vpi_revents;
2621 		vp->v_pollinfo.vpi_revents &= ~events;
2622 
2623 		simple_unlock(&vp->v_pollinfo.vpi_lock);
2624 		return events;
2625 	}
2626 	vp->v_pollinfo.vpi_events |= events;
2627 	selrecord(p, &vp->v_pollinfo.vpi_selinfo);
2628 	simple_unlock(&vp->v_pollinfo.vpi_lock);
2629 	return 0;
2630 }
2631 
2632 /*
2633  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
2634  * it is possible for us to miss an event due to race conditions, but
2635  * that condition is expected to be rare, so for the moment it is the
2636  * preferred interface.
2637  */
2638 void
2639 vn_pollevent(vp, events)
2640 	struct vnode *vp;
2641 	short events;
2642 {
2643 	simple_lock(&vp->v_pollinfo.vpi_lock);
2644 	if (vp->v_pollinfo.vpi_events & events) {
2645 		/*
2646 		 * We clear vpi_events so that we don't
2647 		 * call selwakeup() twice if two events are
2648 		 * posted before the polling process(es) is
2649 		 * awakened.  This also ensures that we take at
2650 		 * most one selwakeup() if the polling process
2651 		 * is no longer interested.  However, it does
2652 		 * mean that only one event can be noticed at
2653 		 * a time.  (Perhaps we should only clear those
2654 		 * event bits which we note?) XXX
2655 		 */
2656 		vp->v_pollinfo.vpi_events = 0;	/* &= ~events ??? */
2657 		vp->v_pollinfo.vpi_revents |= events;
2658 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2659 	}
2660 	simple_unlock(&vp->v_pollinfo.vpi_lock);
2661 }
2662 
2663 /*
2664  * Wake up anyone polling on vp because it is being revoked.
2665  * This depends on dead_poll() returning POLLHUP for correct
2666  * behavior.
2667  */
2668 void
2669 vn_pollgone(vp)
2670 	struct vnode *vp;
2671 {
2672 	simple_lock(&vp->v_pollinfo.vpi_lock);
2673 	if (vp->v_pollinfo.vpi_events) {
2674 		vp->v_pollinfo.vpi_events = 0;
2675 		selwakeup(&vp->v_pollinfo.vpi_selinfo);
2676 	}
2677 	simple_unlock(&vp->v_pollinfo.vpi_lock);
2678 }
2679 
2680 
2681 
2682 /*
2683  * Routine to create and manage a filesystem syncer vnode.
2684  */
2685 #define sync_close ((int (*) __P((struct  vop_close_args *)))nullop)
2686 static int	sync_fsync __P((struct  vop_fsync_args *));
2687 static int	sync_inactive __P((struct  vop_inactive_args *));
2688 static int	sync_reclaim  __P((struct  vop_reclaim_args *));
2689 #define sync_lock ((int (*) __P((struct  vop_lock_args *)))vop_nolock)
2690 #define sync_unlock ((int (*) __P((struct  vop_unlock_args *)))vop_nounlock)
2691 static int	sync_print __P((struct vop_print_args *));
2692 #define sync_islocked ((int(*) __P((struct vop_islocked_args *)))vop_noislocked)
2693 
2694 static vop_t **sync_vnodeop_p;
2695 static struct vnodeopv_entry_desc sync_vnodeop_entries[] = {
2696 	{ &vop_default_desc,	(vop_t *) vop_eopnotsupp },
2697 	{ &vop_close_desc,	(vop_t *) sync_close },		/* close */
2698 	{ &vop_fsync_desc,	(vop_t *) sync_fsync },		/* fsync */
2699 	{ &vop_inactive_desc,	(vop_t *) sync_inactive },	/* inactive */
2700 	{ &vop_reclaim_desc,	(vop_t *) sync_reclaim },	/* reclaim */
2701 	{ &vop_lock_desc,	(vop_t *) sync_lock },		/* lock */
2702 	{ &vop_unlock_desc,	(vop_t *) sync_unlock },	/* unlock */
2703 	{ &vop_print_desc,	(vop_t *) sync_print },		/* print */
2704 	{ &vop_islocked_desc,	(vop_t *) sync_islocked },	/* islocked */
2705 	{ NULL, NULL }
2706 };
2707 static struct vnodeopv_desc sync_vnodeop_opv_desc =
2708 	{ &sync_vnodeop_p, sync_vnodeop_entries };
2709 
2710 VNODEOP_SET(sync_vnodeop_opv_desc);
2711 
2712 /*
2713  * Create a new filesystem syncer vnode for the specified mount point.
2714  */
2715 int
2716 vfs_allocate_syncvnode(mp)
2717 	struct mount *mp;
2718 {
2719 	struct vnode *vp;
2720 	static long start, incr, next;
2721 	int error;
2722 
2723 	/* Allocate a new vnode */
2724 	if ((error = getnewvnode(VT_VFS, mp, sync_vnodeop_p, &vp)) != 0) {
2725 		mp->mnt_syncer = NULL;
2726 		return (error);
2727 	}
2728 	vp->v_type = VNON;
2729 	/*
2730 	 * Place the vnode onto the syncer worklist. We attempt to
2731 	 * scatter them about on the list so that they will go off
2732 	 * at evenly distributed times even if all the filesystems
2733 	 * are mounted at once.
2734 	 */
2735 	next += incr;
2736 	if (next == 0 || next > syncer_maxdelay) {
2737 		start /= 2;
2738 		incr /= 2;
2739 		if (start == 0) {
2740 			start = syncer_maxdelay / 2;
2741 			incr = syncer_maxdelay;
2742 		}
2743 		next = start;
2744 	}
2745 	vn_syncer_add_to_worklist(vp, syncdelay > 0 ? next % syncdelay : 0);
2746 	mp->mnt_syncer = vp;
2747 	return (0);
2748 }
2749 
2750 /*
2751  * Do a lazy sync of the filesystem.
2752  */
2753 static int
2754 sync_fsync(ap)
2755 	struct vop_fsync_args /* {
2756 		struct vnode *a_vp;
2757 		struct ucred *a_cred;
2758 		int a_waitfor;
2759 		struct proc *a_p;
2760 	} */ *ap;
2761 {
2762 	struct vnode *syncvp = ap->a_vp;
2763 	struct mount *mp = syncvp->v_mount;
2764 	struct proc *p = ap->a_p;
2765 	int asyncflag;
2766 
2767 	/*
2768 	 * We only need to do something if this is a lazy evaluation.
2769 	 */
2770 	if (ap->a_waitfor != MNT_LAZY)
2771 		return (0);
2772 
2773 	/*
2774 	 * Move ourselves to the back of the sync list.
2775 	 */
2776 	vn_syncer_add_to_worklist(syncvp, syncdelay);
2777 
2778 	/*
2779 	 * Walk the list of vnodes pushing all that are dirty and
2780 	 * not already on the sync list.
2781 	 */
2782 	simple_lock(&mountlist_slock);
2783 	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_slock, p) != 0) {
2784 		simple_unlock(&mountlist_slock);
2785 		return (0);
2786 	}
2787 	asyncflag = mp->mnt_flag & MNT_ASYNC;
2788 	mp->mnt_flag &= ~MNT_ASYNC;
2789 	vfs_msync(mp, MNT_NOWAIT);
2790 	VFS_SYNC(mp, MNT_LAZY, ap->a_cred, p);
2791 	if (asyncflag)
2792 		mp->mnt_flag |= MNT_ASYNC;
2793 	vfs_unbusy(mp, p);
2794 	return (0);
2795 }
2796 
2797 /*
2798  * The syncer vnode is no referenced.
2799  */
2800 static int
2801 sync_inactive(ap)
2802 	struct vop_inactive_args /* {
2803 		struct vnode *a_vp;
2804 		struct proc *a_p;
2805 	} */ *ap;
2806 {
2807 
2808 	vgone(ap->a_vp);
2809 	return (0);
2810 }
2811 
2812 /*
2813  * The syncer vnode is no longer needed and is being decommissioned.
2814  *
2815  * Modifications to the worklist must be protected at splbio().
2816  */
2817 static int
2818 sync_reclaim(ap)
2819 	struct vop_reclaim_args /* {
2820 		struct vnode *a_vp;
2821 	} */ *ap;
2822 {
2823 	struct vnode *vp = ap->a_vp;
2824 	int s;
2825 
2826 	s = splbio();
2827 	vp->v_mount->mnt_syncer = NULL;
2828 	if (vp->v_flag & VONWORKLST) {
2829 		LIST_REMOVE(vp, v_synclist);
2830 		vp->v_flag &= ~VONWORKLST;
2831 	}
2832 	splx(s);
2833 
2834 	return (0);
2835 }
2836 
2837 /*
2838  * Print out a syncer vnode.
2839  */
2840 static int
2841 sync_print(ap)
2842 	struct vop_print_args /* {
2843 		struct vnode *a_vp;
2844 	} */ *ap;
2845 {
2846 	struct vnode *vp = ap->a_vp;
2847 
2848 	printf("syncer vnode");
2849 	if (vp->v_vnlock != NULL)
2850 		lockmgr_printinfo(vp->v_vnlock);
2851 	printf("\n");
2852 	return (0);
2853 }
2854 
2855 /*
2856  * extract the dev_t from a VBLK or VCHR
2857  */
2858 dev_t
2859 vn_todev(vp)
2860 	struct vnode *vp;
2861 {
2862 	if (vp->v_type != VBLK && vp->v_type != VCHR)
2863 		return (NODEV);
2864 	return (vp->v_rdev);
2865 }
2866 
2867 /*
2868  * Check if vnode represents a disk device
2869  */
2870 int
2871 vn_isdisk(vp)
2872 	struct vnode *vp;
2873 {
2874 	if (vp->v_type != VBLK)
2875 		return (0);
2876 	if (!devsw(vp->v_rdev))
2877 		return (0);
2878 	if (!(devsw(vp->v_rdev)->d_flags & D_DISK))
2879 		return (0);
2880 	return (1);
2881 }
2882 
2883