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