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