xref: /freebsd/sys/kern/vfs_subr.c (revision 51a9219f5780e61e1437d25220bf8750d9df7f8b)
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 /*
1958  * Add vnode to the alias list hung off the dev_t.
1959  *
1960  * The reason for this gunk is that multiple vnodes can reference
1961  * the same physical device, so checking vp->v_usecount to see
1962  * how many users there are is inadequate; the v_usecount for
1963  * the vnodes need to be accumulated.  vcount() does that.
1964  */
1965 struct vnode *
1966 addaliasu(nvp, nvp_rdev)
1967 	struct vnode *nvp;
1968 	udev_t nvp_rdev;
1969 {
1970 	struct vnode *ovp;
1971 	vop_t **ops;
1972 	dev_t dev;
1973 
1974 	if (nvp->v_type == VBLK)
1975 		return (nvp);
1976 	if (nvp->v_type != VCHR)
1977 		panic("addaliasu on non-special vnode");
1978 	dev = udev2dev(nvp_rdev, 0);
1979 	/*
1980 	 * Check to see if we have a bdevvp vnode with no associated
1981 	 * filesystem. If so, we want to associate the filesystem of
1982 	 * the new newly instigated vnode with the bdevvp vnode and
1983 	 * discard the newly created vnode rather than leaving the
1984 	 * bdevvp vnode lying around with no associated filesystem.
1985 	 */
1986 	if (vfinddev(dev, nvp->v_type, &ovp) == 0 || ovp->v_data != NULL) {
1987 		addalias(nvp, dev);
1988 		return (nvp);
1989 	}
1990 	/*
1991 	 * Discard unneeded vnode, but save its node specific data.
1992 	 * Note that if there is a lock, it is carried over in the
1993 	 * node specific data to the replacement vnode.
1994 	 */
1995 	vref(ovp);
1996 	ovp->v_data = nvp->v_data;
1997 	ovp->v_tag = nvp->v_tag;
1998 	nvp->v_data = NULL;
1999 	lockdestroy(ovp->v_vnlock);
2000 	lockinit(ovp->v_vnlock, PVFS, nvp->v_vnlock->lk_wmesg,
2001 	    nvp->v_vnlock->lk_timo, nvp->v_vnlock->lk_flags & LK_EXTFLG_MASK);
2002 	ops = ovp->v_op;
2003 	ovp->v_op = nvp->v_op;
2004 	if (VOP_ISLOCKED(nvp, curthread)) {
2005 		VOP_UNLOCK(nvp, 0, curthread);
2006 		vn_lock(ovp, LK_EXCLUSIVE | LK_RETRY, curthread);
2007 	}
2008 	nvp->v_op = ops;
2009 	insmntque(ovp, nvp->v_mount);
2010 	vrele(nvp);
2011 	vgone(nvp);
2012 	return (ovp);
2013 }
2014 
2015 /* This is a local helper function that do the same as addaliasu, but for a
2016  * dev_t instead of an udev_t. */
2017 static void
2018 addalias(nvp, dev)
2019 	struct vnode *nvp;
2020 	dev_t dev;
2021 {
2022 
2023 	KASSERT(nvp->v_type == VCHR, ("addalias on non-special vnode"));
2024 	nvp->v_rdev = dev;
2025 	mtx_lock(&spechash_mtx);
2026 	SLIST_INSERT_HEAD(&dev->si_hlist, nvp, v_specnext);
2027 	mtx_unlock(&spechash_mtx);
2028 }
2029 
2030 /*
2031  * Grab a particular vnode from the free list, increment its
2032  * reference count and lock it. The vnode lock bit is set if the
2033  * vnode is being eliminated in vgone. The process is awakened
2034  * when the transition is completed, and an error returned to
2035  * indicate that the vnode is no longer usable (possibly having
2036  * been changed to a new filesystem type).
2037  */
2038 int
2039 vget(vp, flags, td)
2040 	register struct vnode *vp;
2041 	int flags;
2042 	struct thread *td;
2043 {
2044 	int error;
2045 
2046 	/*
2047 	 * If the vnode is in the process of being cleaned out for
2048 	 * another use, we wait for the cleaning to finish and then
2049 	 * return failure. Cleaning is determined by checking that
2050 	 * the VI_XLOCK flag is set.
2051 	 */
2052 	if ((flags & LK_INTERLOCK) == 0)
2053 		VI_LOCK(vp);
2054 	if (vp->v_iflag & VI_XLOCK && vp->v_vxproc != curthread) {
2055 		vp->v_iflag |= VI_XWANT;
2056 		msleep(vp, VI_MTX(vp), PINOD | PDROP, "vget", 0);
2057 		return (ENOENT);
2058 	}
2059 
2060 	vp->v_usecount++;
2061 
2062 	if (VSHOULDBUSY(vp))
2063 		vbusy(vp);
2064 	if (flags & LK_TYPE_MASK) {
2065 		if ((error = vn_lock(vp, flags | LK_INTERLOCK, td)) != 0) {
2066 			/*
2067 			 * must expand vrele here because we do not want
2068 			 * to call VOP_INACTIVE if the reference count
2069 			 * drops back to zero since it was never really
2070 			 * active. We must remove it from the free list
2071 			 * before sleeping so that multiple processes do
2072 			 * not try to recycle it.
2073 			 */
2074 			VI_LOCK(vp);
2075 			vp->v_usecount--;
2076 			if (VSHOULDFREE(vp))
2077 				vfree(vp);
2078 			else
2079 				vlruvp(vp);
2080 			VI_UNLOCK(vp);
2081 		}
2082 		return (error);
2083 	}
2084 	VI_UNLOCK(vp);
2085 	return (0);
2086 }
2087 
2088 /*
2089  * Increase the reference count of a vnode.
2090  */
2091 void
2092 vref(struct vnode *vp)
2093 {
2094 	VI_LOCK(vp);
2095 	vp->v_usecount++;
2096 	VI_UNLOCK(vp);
2097 }
2098 
2099 /*
2100  * Return reference count of a vnode.
2101  *
2102  * The results of this call are only guaranteed when some mechanism other
2103  * than the VI lock is used to stop other processes from gaining references
2104  * to the vnode.  This may be the case if the caller holds the only reference.
2105  * This is also useful when stale data is acceptable as race conditions may
2106  * be accounted for by some other means.
2107  */
2108 int
2109 vrefcnt(struct vnode *vp)
2110 {
2111 	int usecnt;
2112 
2113 	VI_LOCK(vp);
2114 	usecnt = vp->v_usecount;
2115 	VI_UNLOCK(vp);
2116 
2117 	return (usecnt);
2118 }
2119 
2120 
2121 /*
2122  * Vnode put/release.
2123  * If count drops to zero, call inactive routine and return to freelist.
2124  */
2125 void
2126 vrele(vp)
2127 	struct vnode *vp;
2128 {
2129 	struct thread *td = curthread;	/* XXX */
2130 
2131 	KASSERT(vp != NULL, ("vrele: null vp"));
2132 
2133 	VI_LOCK(vp);
2134 
2135 	/* Skip this v_writecount check if we're going to panic below. */
2136 	KASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1,
2137 	    ("vrele: missed vn_close"));
2138 
2139 	if (vp->v_usecount > 1) {
2140 
2141 		vp->v_usecount--;
2142 		VI_UNLOCK(vp);
2143 
2144 		return;
2145 	}
2146 
2147 	if (vp->v_usecount == 1) {
2148 		vp->v_usecount--;
2149 		/*
2150 		 * We must call VOP_INACTIVE with the node locked.
2151 		 * If we are doing a vput, the node is already locked,
2152 		 * but, in the case of vrele, we must explicitly lock
2153 		 * the vnode before calling VOP_INACTIVE.
2154 		 */
2155 		if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK, td) == 0)
2156 			VOP_INACTIVE(vp, td);
2157 		VI_LOCK(vp);
2158 		if (VSHOULDFREE(vp))
2159 			vfree(vp);
2160 		else
2161 			vlruvp(vp);
2162 		VI_UNLOCK(vp);
2163 
2164 	} else {
2165 #ifdef DIAGNOSTIC
2166 		vprint("vrele: negative ref count", vp);
2167 #endif
2168 		VI_UNLOCK(vp);
2169 		panic("vrele: negative ref cnt");
2170 	}
2171 }
2172 
2173 /*
2174  * Release an already locked vnode.  This give the same effects as
2175  * unlock+vrele(), but takes less time and avoids releasing and
2176  * re-aquiring the lock (as vrele() aquires the lock internally.)
2177  */
2178 void
2179 vput(vp)
2180 	struct vnode *vp;
2181 {
2182 	struct thread *td = curthread;	/* XXX */
2183 
2184 	GIANT_REQUIRED;
2185 
2186 	KASSERT(vp != NULL, ("vput: null vp"));
2187 	VI_LOCK(vp);
2188 	/* Skip this v_writecount check if we're going to panic below. */
2189 	KASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1,
2190 	    ("vput: missed vn_close"));
2191 
2192 	if (vp->v_usecount > 1) {
2193 		vp->v_usecount--;
2194 		VOP_UNLOCK(vp, LK_INTERLOCK, td);
2195 		return;
2196 	}
2197 
2198 	if (vp->v_usecount == 1) {
2199 		vp->v_usecount--;
2200 		/*
2201 		 * We must call VOP_INACTIVE with the node locked.
2202 		 * If we are doing a vput, the node is already locked,
2203 		 * so we just need to release the vnode mutex.
2204 		 */
2205 		VI_UNLOCK(vp);
2206 		VOP_INACTIVE(vp, td);
2207 		VI_LOCK(vp);
2208 		if (VSHOULDFREE(vp))
2209 			vfree(vp);
2210 		else
2211 			vlruvp(vp);
2212 		VI_UNLOCK(vp);
2213 
2214 	} else {
2215 #ifdef DIAGNOSTIC
2216 		vprint("vput: negative ref count", vp);
2217 #endif
2218 		panic("vput: negative ref cnt");
2219 	}
2220 }
2221 
2222 /*
2223  * Somebody doesn't want the vnode recycled.
2224  */
2225 void
2226 vhold(struct vnode *vp)
2227 {
2228 	VI_LOCK(vp);
2229 	vholdl(vp);
2230 	VI_UNLOCK(vp);
2231 }
2232 
2233 void
2234 vholdl(vp)
2235 	register struct vnode *vp;
2236 {
2237 	int s;
2238 
2239 	s = splbio();
2240 	vp->v_holdcnt++;
2241 	if (VSHOULDBUSY(vp))
2242 		vbusy(vp);
2243 	splx(s);
2244 }
2245 
2246 /*
2247  * Note that there is one less who cares about this vnode.  vdrop() is the
2248  * opposite of vhold().
2249  */
2250 void
2251 vdrop(struct vnode *vp)
2252 {
2253 	VI_LOCK(vp);
2254 	vdropl(vp);
2255 	VI_UNLOCK(vp);
2256 }
2257 
2258 void
2259 vdropl(vp)
2260 	register struct vnode *vp;
2261 {
2262 	int s;
2263 
2264 	s = splbio();
2265 	if (vp->v_holdcnt <= 0)
2266 		panic("vdrop: holdcnt");
2267 	vp->v_holdcnt--;
2268 	if (VSHOULDFREE(vp))
2269 		vfree(vp);
2270 	else
2271 		vlruvp(vp);
2272 	splx(s);
2273 }
2274 
2275 /*
2276  * Remove any vnodes in the vnode table belonging to mount point mp.
2277  *
2278  * If FORCECLOSE is not specified, there should not be any active ones,
2279  * return error if any are found (nb: this is a user error, not a
2280  * system error). If FORCECLOSE is specified, detach any active vnodes
2281  * that are found.
2282  *
2283  * If WRITECLOSE is set, only flush out regular file vnodes open for
2284  * writing.
2285  *
2286  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2287  *
2288  * `rootrefs' specifies the base reference count for the root vnode
2289  * of this filesystem. The root vnode is considered busy if its
2290  * v_usecount exceeds this value. On a successful return, vflush()
2291  * will call vrele() on the root vnode exactly rootrefs times.
2292  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2293  * be zero.
2294  */
2295 #ifdef DIAGNOSTIC
2296 static int busyprt = 0;		/* print out busy vnodes */
2297 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
2298 #endif
2299 
2300 int
2301 vflush(mp, rootrefs, flags)
2302 	struct mount *mp;
2303 	int rootrefs;
2304 	int flags;
2305 {
2306 	struct thread *td = curthread;	/* XXX */
2307 	struct vnode *vp, *nvp, *rootvp = NULL;
2308 	struct vattr vattr;
2309 	int busy = 0, error;
2310 
2311 	if (rootrefs > 0) {
2312 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2313 		    ("vflush: bad args"));
2314 		/*
2315 		 * Get the filesystem root vnode. We can vput() it
2316 		 * immediately, since with rootrefs > 0, it won't go away.
2317 		 */
2318 		if ((error = VFS_ROOT(mp, &rootvp)) != 0)
2319 			return (error);
2320 		vput(rootvp);
2321 
2322 	}
2323 	mtx_lock(&mntvnode_mtx);
2324 loop:
2325 	for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp; vp = nvp) {
2326 		/*
2327 		 * Make sure this vnode wasn't reclaimed in getnewvnode().
2328 		 * Start over if it has (it won't be on the list anymore).
2329 		 */
2330 		if (vp->v_mount != mp)
2331 			goto loop;
2332 		nvp = TAILQ_NEXT(vp, v_nmntvnodes);
2333 
2334 		VI_LOCK(vp);
2335 		mtx_unlock(&mntvnode_mtx);
2336 		vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE | LK_RETRY, td);
2337 		/*
2338 		 * Skip over a vnodes marked VV_SYSTEM.
2339 		 */
2340 		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2341 			VOP_UNLOCK(vp, 0, td);
2342 			mtx_lock(&mntvnode_mtx);
2343 			continue;
2344 		}
2345 		/*
2346 		 * If WRITECLOSE is set, flush out unlinked but still open
2347 		 * files (even if open only for reading) and regular file
2348 		 * vnodes open for writing.
2349 		 */
2350 		if (flags & WRITECLOSE) {
2351 			error = VOP_GETATTR(vp, &vattr, td->td_ucred, td);
2352 			VI_LOCK(vp);
2353 
2354 			if ((vp->v_type == VNON ||
2355 			    (error == 0 && vattr.va_nlink > 0)) &&
2356 			    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2357 				VOP_UNLOCK(vp, LK_INTERLOCK, td);
2358 				mtx_lock(&mntvnode_mtx);
2359 				continue;
2360 			}
2361 		} else
2362 			VI_LOCK(vp);
2363 
2364 		VOP_UNLOCK(vp, 0, td);
2365 
2366 		/*
2367 		 * With v_usecount == 0, all we need to do is clear out the
2368 		 * vnode data structures and we are done.
2369 		 */
2370 		if (vp->v_usecount == 0) {
2371 			vgonel(vp, td);
2372 			mtx_lock(&mntvnode_mtx);
2373 			continue;
2374 		}
2375 
2376 		/*
2377 		 * If FORCECLOSE is set, forcibly close the vnode. For block
2378 		 * or character devices, revert to an anonymous device. For
2379 		 * all other files, just kill them.
2380 		 */
2381 		if (flags & FORCECLOSE) {
2382 			if (vp->v_type != VCHR) {
2383 				vgonel(vp, td);
2384 			} else {
2385 				vclean(vp, 0, td);
2386 				VI_UNLOCK(vp);
2387 				vp->v_op = spec_vnodeop_p;
2388 				insmntque(vp, (struct mount *) 0);
2389 			}
2390 			mtx_lock(&mntvnode_mtx);
2391 			continue;
2392 		}
2393 #ifdef DIAGNOSTIC
2394 		if (busyprt)
2395 			vprint("vflush: busy vnode", vp);
2396 #endif
2397 		VI_UNLOCK(vp);
2398 		mtx_lock(&mntvnode_mtx);
2399 		busy++;
2400 	}
2401 	mtx_unlock(&mntvnode_mtx);
2402 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2403 		/*
2404 		 * If just the root vnode is busy, and if its refcount
2405 		 * is equal to `rootrefs', then go ahead and kill it.
2406 		 */
2407 		VI_LOCK(rootvp);
2408 		KASSERT(busy > 0, ("vflush: not busy"));
2409 		KASSERT(rootvp->v_usecount >= rootrefs, ("vflush: rootrefs"));
2410 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
2411 			vgonel(rootvp, td);
2412 			busy = 0;
2413 		} else
2414 			VI_UNLOCK(rootvp);
2415 	}
2416 	if (busy)
2417 		return (EBUSY);
2418 	for (; rootrefs > 0; rootrefs--)
2419 		vrele(rootvp);
2420 	return (0);
2421 }
2422 
2423 /*
2424  * This moves a now (likely recyclable) vnode to the end of the
2425  * mountlist.  XXX However, it is temporarily disabled until we
2426  * can clean up ffs_sync() and friends, which have loop restart
2427  * conditions which this code causes to operate O(N^2).
2428  */
2429 static void
2430 vlruvp(struct vnode *vp)
2431 {
2432 #if 0
2433 	struct mount *mp;
2434 
2435 	if ((mp = vp->v_mount) != NULL) {
2436 		mtx_lock(&mntvnode_mtx);
2437 		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2438 		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
2439 		mtx_unlock(&mntvnode_mtx);
2440 	}
2441 #endif
2442 }
2443 
2444 /*
2445  * Disassociate the underlying filesystem from a vnode.
2446  */
2447 static void
2448 vclean(vp, flags, td)
2449 	struct vnode *vp;
2450 	int flags;
2451 	struct thread *td;
2452 {
2453 	int active;
2454 
2455 	ASSERT_VI_LOCKED(vp, "vclean");
2456 	/*
2457 	 * Check to see if the vnode is in use. If so we have to reference it
2458 	 * before we clean it out so that its count cannot fall to zero and
2459 	 * generate a race against ourselves to recycle it.
2460 	 */
2461 	if ((active = vp->v_usecount))
2462 		vp->v_usecount++;
2463 
2464 	/*
2465 	 * Prevent the vnode from being recycled or brought into use while we
2466 	 * clean it out.
2467 	 */
2468 	if (vp->v_iflag & VI_XLOCK)
2469 		panic("vclean: deadlock");
2470 	vp->v_iflag |= VI_XLOCK;
2471 	vp->v_vxproc = curthread;
2472 	/*
2473 	 * Even if the count is zero, the VOP_INACTIVE routine may still
2474 	 * have the object locked while it cleans it out. The VOP_LOCK
2475 	 * ensures that the VOP_INACTIVE routine is done with its work.
2476 	 * For active vnodes, it ensures that no other activity can
2477 	 * occur while the underlying object is being cleaned out.
2478 	 */
2479 	VOP_LOCK(vp, LK_DRAIN | LK_INTERLOCK, td);
2480 
2481 	/*
2482 	 * Clean out any buffers associated with the vnode.
2483 	 * If the flush fails, just toss the buffers.
2484 	 */
2485 	if (flags & DOCLOSE) {
2486 		struct buf *bp;
2487 		VI_LOCK(vp);
2488 		bp = TAILQ_FIRST(&vp->v_dirtyblkhd);
2489 		VI_UNLOCK(vp);
2490 		if (bp != NULL)
2491 			(void) vn_write_suspend_wait(vp, NULL, V_WAIT);
2492 		if (vinvalbuf(vp, V_SAVE, NOCRED, td, 0, 0) != 0)
2493 			vinvalbuf(vp, 0, NOCRED, td, 0, 0);
2494 	}
2495 
2496 	VOP_DESTROYVOBJECT(vp);
2497 
2498 	/*
2499 	 * Any other processes trying to obtain this lock must first
2500 	 * wait for VXLOCK to clear, then call the new lock operation.
2501 	 */
2502 	VOP_UNLOCK(vp, 0, td);
2503 
2504 	/*
2505 	 * If purging an active vnode, it must be closed and
2506 	 * deactivated before being reclaimed. Note that the
2507 	 * VOP_INACTIVE will unlock the vnode.
2508 	 */
2509 	if (active) {
2510 		if (flags & DOCLOSE)
2511 			VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2512 		if (vn_lock(vp, LK_EXCLUSIVE | LK_NOWAIT, td) != 0)
2513 			panic("vclean: cannot relock.");
2514 		VOP_INACTIVE(vp, td);
2515 	}
2516 
2517 	/*
2518 	 * Reclaim the vnode.
2519 	 */
2520 	if (VOP_RECLAIM(vp, td))
2521 		panic("vclean: cannot reclaim");
2522 
2523 	if (active) {
2524 		/*
2525 		 * Inline copy of vrele() since VOP_INACTIVE
2526 		 * has already been called.
2527 		 */
2528 		VI_LOCK(vp);
2529 		if (--vp->v_usecount <= 0) {
2530 #ifdef DIAGNOSTIC
2531 			if (vp->v_usecount < 0 || vp->v_writecount != 0) {
2532 				vprint("vclean: bad ref count", vp);
2533 				panic("vclean: ref cnt");
2534 			}
2535 #endif
2536 			vfree(vp);
2537 		}
2538 		VI_UNLOCK(vp);
2539 	}
2540 
2541 	cache_purge(vp);
2542 	VI_LOCK(vp);
2543 	if (VSHOULDFREE(vp))
2544 		vfree(vp);
2545 
2546 	/*
2547 	 * Done with purge, reset to the standard lock and
2548 	 * notify sleepers of the grim news.
2549 	 */
2550 	vp->v_vnlock = &vp->v_lock;
2551 	vp->v_op = dead_vnodeop_p;
2552 	if (vp->v_pollinfo != NULL)
2553 		vn_pollgone(vp);
2554 	vp->v_tag = "none";
2555 	vp->v_iflag &= ~VI_XLOCK;
2556 	vp->v_vxproc = NULL;
2557 	if (vp->v_iflag & VI_XWANT) {
2558 		vp->v_iflag &= ~VI_XWANT;
2559 		wakeup(vp);
2560 	}
2561 }
2562 
2563 /*
2564  * Eliminate all activity associated with the requested vnode
2565  * and with all vnodes aliased to the requested vnode.
2566  */
2567 int
2568 vop_revoke(ap)
2569 	struct vop_revoke_args /* {
2570 		struct vnode *a_vp;
2571 		int a_flags;
2572 	} */ *ap;
2573 {
2574 	struct vnode *vp, *vq;
2575 	dev_t dev;
2576 
2577 	KASSERT((ap->a_flags & REVOKEALL) != 0, ("vop_revoke"));
2578 
2579 	vp = ap->a_vp;
2580 	VI_LOCK(vp);
2581 	/*
2582 	 * If a vgone (or vclean) is already in progress,
2583 	 * wait until it is done and return.
2584 	 */
2585 	if (vp->v_iflag & VI_XLOCK) {
2586 		vp->v_iflag |= VI_XWANT;
2587 		msleep(vp, VI_MTX(vp), PINOD | PDROP,
2588 		    "vop_revokeall", 0);
2589 		return (0);
2590 	}
2591 	VI_UNLOCK(vp);
2592 	dev = vp->v_rdev;
2593 	for (;;) {
2594 		mtx_lock(&spechash_mtx);
2595 		vq = SLIST_FIRST(&dev->si_hlist);
2596 		mtx_unlock(&spechash_mtx);
2597 		if (!vq)
2598 			break;
2599 		vgone(vq);
2600 	}
2601 	return (0);
2602 }
2603 
2604 /*
2605  * Recycle an unused vnode to the front of the free list.
2606  * Release the passed interlock if the vnode will be recycled.
2607  */
2608 int
2609 vrecycle(vp, inter_lkp, td)
2610 	struct vnode *vp;
2611 	struct mtx *inter_lkp;
2612 	struct thread *td;
2613 {
2614 
2615 	VI_LOCK(vp);
2616 	if (vp->v_usecount == 0) {
2617 		if (inter_lkp) {
2618 			mtx_unlock(inter_lkp);
2619 		}
2620 		vgonel(vp, td);
2621 		return (1);
2622 	}
2623 	VI_UNLOCK(vp);
2624 	return (0);
2625 }
2626 
2627 /*
2628  * Eliminate all activity associated with a vnode
2629  * in preparation for reuse.
2630  */
2631 void
2632 vgone(vp)
2633 	register struct vnode *vp;
2634 {
2635 	struct thread *td = curthread;	/* XXX */
2636 
2637 	VI_LOCK(vp);
2638 	vgonel(vp, td);
2639 }
2640 
2641 /*
2642  * vgone, with the vp interlock held.
2643  */
2644 void
2645 vgonel(vp, td)
2646 	struct vnode *vp;
2647 	struct thread *td;
2648 {
2649 	int s;
2650 
2651 	/*
2652 	 * If a vgone (or vclean) is already in progress,
2653 	 * wait until it is done and return.
2654 	 */
2655 	ASSERT_VI_LOCKED(vp, "vgonel");
2656 	if (vp->v_iflag & VI_XLOCK) {
2657 		vp->v_iflag |= VI_XWANT;
2658 		msleep(vp, VI_MTX(vp), PINOD | PDROP, "vgone", 0);
2659 		return;
2660 	}
2661 
2662 	/*
2663 	 * Clean out the filesystem specific data.
2664 	 */
2665 	vclean(vp, DOCLOSE, td);
2666 	VI_UNLOCK(vp);
2667 
2668 	/*
2669 	 * Delete from old mount point vnode list, if on one.
2670 	 */
2671 	if (vp->v_mount != NULL)
2672 		insmntque(vp, (struct mount *)0);
2673 	/*
2674 	 * If special device, remove it from special device alias list
2675 	 * if it is on one.
2676 	 */
2677 	if (vp->v_type == VCHR && vp->v_rdev != NULL && vp->v_rdev != NODEV) {
2678 		mtx_lock(&spechash_mtx);
2679 		SLIST_REMOVE(&vp->v_rdev->si_hlist, vp, vnode, v_specnext);
2680 		freedev(vp->v_rdev);
2681 		mtx_unlock(&spechash_mtx);
2682 		vp->v_rdev = NULL;
2683 	}
2684 
2685 	/*
2686 	 * If it is on the freelist and not already at the head,
2687 	 * move it to the head of the list. The test of the
2688 	 * VDOOMED flag and the reference count of zero is because
2689 	 * it will be removed from the free list by getnewvnode,
2690 	 * but will not have its reference count incremented until
2691 	 * after calling vgone. If the reference count were
2692 	 * incremented first, vgone would (incorrectly) try to
2693 	 * close the previous instance of the underlying object.
2694 	 */
2695 	VI_LOCK(vp);
2696 	if (vp->v_usecount == 0 && !(vp->v_iflag & VI_DOOMED)) {
2697 		s = splbio();
2698 		mtx_lock(&vnode_free_list_mtx);
2699 		if (vp->v_iflag & VI_FREE) {
2700 			TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
2701 		} else {
2702 			vp->v_iflag |= VI_FREE;
2703 			freevnodes++;
2704 		}
2705 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
2706 		mtx_unlock(&vnode_free_list_mtx);
2707 		splx(s);
2708 	}
2709 
2710 	vp->v_type = VBAD;
2711 	VI_UNLOCK(vp);
2712 }
2713 
2714 /*
2715  * Lookup a vnode by device number.
2716  */
2717 int
2718 vfinddev(dev, type, vpp)
2719 	dev_t dev;
2720 	enum vtype type;
2721 	struct vnode **vpp;
2722 {
2723 	struct vnode *vp;
2724 
2725 	mtx_lock(&spechash_mtx);
2726 	SLIST_FOREACH(vp, &dev->si_hlist, v_specnext) {
2727 		if (type == vp->v_type) {
2728 			*vpp = vp;
2729 			mtx_unlock(&spechash_mtx);
2730 			return (1);
2731 		}
2732 	}
2733 	mtx_unlock(&spechash_mtx);
2734 	return (0);
2735 }
2736 
2737 /*
2738  * Calculate the total number of references to a special device.
2739  */
2740 int
2741 vcount(vp)
2742 	struct vnode *vp;
2743 {
2744 	struct vnode *vq;
2745 	int count;
2746 
2747 	count = 0;
2748 	mtx_lock(&spechash_mtx);
2749 	SLIST_FOREACH(vq, &vp->v_rdev->si_hlist, v_specnext) {
2750 		if (vq != vp)
2751 			VI_LOCK(vq);
2752 		count += vq->v_usecount;
2753 		if (vq != vp)
2754 			VI_UNLOCK(vq);
2755 	}
2756 	mtx_unlock(&spechash_mtx);
2757 	return (count);
2758 }
2759 
2760 /*
2761  * Same as above, but using the dev_t as argument
2762  */
2763 int
2764 count_dev(dev)
2765 	dev_t dev;
2766 {
2767 	struct vnode *vp;
2768 
2769 	vp = SLIST_FIRST(&dev->si_hlist);
2770 	if (vp == NULL)
2771 		return (0);
2772 	return(vcount(vp));
2773 }
2774 
2775 /*
2776  * Print out a description of a vnode.
2777  */
2778 static char *typename[] =
2779 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD"};
2780 
2781 void
2782 vprint(label, vp)
2783 	char *label;
2784 	struct vnode *vp;
2785 {
2786 	char buf[96];
2787 
2788 	if (label != NULL)
2789 		printf("%s: %p: ", label, (void *)vp);
2790 	else
2791 		printf("%p: ", (void *)vp);
2792 	printf("tag %s, type %s, usecount %d, writecount %d, refcount %d,",
2793 	    vp->v_tag, typename[vp->v_type], vp->v_usecount,
2794 	    vp->v_writecount, vp->v_holdcnt);
2795 	buf[0] = '\0';
2796 	if (vp->v_vflag & VV_ROOT)
2797 		strcat(buf, "|VV_ROOT");
2798 	if (vp->v_vflag & VV_TEXT)
2799 		strcat(buf, "|VV_TEXT");
2800 	if (vp->v_vflag & VV_SYSTEM)
2801 		strcat(buf, "|VV_SYSTEM");
2802 	if (vp->v_iflag & VI_XLOCK)
2803 		strcat(buf, "|VI_XLOCK");
2804 	if (vp->v_iflag & VI_XWANT)
2805 		strcat(buf, "|VI_XWANT");
2806 	if (vp->v_iflag & VI_BWAIT)
2807 		strcat(buf, "|VI_BWAIT");
2808 	if (vp->v_iflag & VI_DOOMED)
2809 		strcat(buf, "|VI_DOOMED");
2810 	if (vp->v_iflag & VI_FREE)
2811 		strcat(buf, "|VI_FREE");
2812 	if (vp->v_vflag & VV_OBJBUF)
2813 		strcat(buf, "|VV_OBJBUF");
2814 	if (buf[0] != '\0')
2815 		printf(" flags (%s),", &buf[1]);
2816 	lockmgr_printinfo(vp->v_vnlock);
2817 	printf("\n");
2818 	if (vp->v_data != NULL) {
2819 		printf("\t");
2820 		VOP_PRINT(vp);
2821 	}
2822 }
2823 
2824 #ifdef DDB
2825 #include <ddb/ddb.h>
2826 /*
2827  * List all of the locked vnodes in the system.
2828  * Called when debugging the kernel.
2829  */
2830 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2831 {
2832 	struct thread *td = curthread;	/* XXX */
2833 	struct mount *mp, *nmp;
2834 	struct vnode *vp;
2835 
2836 	printf("Locked vnodes\n");
2837 	mtx_lock(&mountlist_mtx);
2838 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2839 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td)) {
2840 			nmp = TAILQ_NEXT(mp, mnt_list);
2841 			continue;
2842 		}
2843 		mtx_lock(&mntvnode_mtx);
2844 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2845 			if (VOP_ISLOCKED(vp, NULL))
2846 				vprint((char *)0, vp);
2847 		}
2848 		mtx_unlock(&mntvnode_mtx);
2849 		mtx_lock(&mountlist_mtx);
2850 		nmp = TAILQ_NEXT(mp, mnt_list);
2851 		vfs_unbusy(mp, td);
2852 	}
2853 	mtx_unlock(&mountlist_mtx);
2854 }
2855 #endif
2856 
2857 /*
2858  * Fill in a struct xvfsconf based on a struct vfsconf.
2859  */
2860 static void
2861 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
2862 {
2863 
2864 	strcpy(xvfsp->vfc_name, vfsp->vfc_name);
2865 	xvfsp->vfc_typenum = vfsp->vfc_typenum;
2866 	xvfsp->vfc_refcount = vfsp->vfc_refcount;
2867 	xvfsp->vfc_flags = vfsp->vfc_flags;
2868 	/*
2869 	 * These are unused in userland, we keep them
2870 	 * to not break binary compatibility.
2871 	 */
2872 	xvfsp->vfc_vfsops = NULL;
2873 	xvfsp->vfc_next = NULL;
2874 }
2875 
2876 static int
2877 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
2878 {
2879 	struct vfsconf *vfsp;
2880 	struct xvfsconf *xvfsp;
2881 	int cnt, error, i;
2882 
2883 	cnt = 0;
2884 	for (vfsp = vfsconf; vfsp != NULL; vfsp = vfsp->vfc_next)
2885 		cnt++;
2886 	xvfsp = malloc(sizeof(struct xvfsconf) * cnt, M_TEMP, M_WAITOK);
2887 	/*
2888 	 * Handle the race that we will have here when struct vfsconf
2889 	 * will be locked down by using both cnt and checking vfc_next
2890 	 * against NULL to determine the end of the loop.  The race will
2891 	 * happen because we will have to unlock before calling malloc().
2892 	 * We are protected by Giant for now.
2893 	 */
2894 	i = 0;
2895 	for (vfsp = vfsconf; vfsp != NULL && i < cnt; vfsp = vfsp->vfc_next) {
2896 		vfsconf2x(vfsp, xvfsp + i);
2897 		i++;
2898 	}
2899 	error = SYSCTL_OUT(req, xvfsp, sizeof(struct xvfsconf) * i);
2900 	free(xvfsp, M_TEMP);
2901 	return (error);
2902 }
2903 
2904 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLFLAG_RD, NULL, 0, sysctl_vfs_conflist,
2905     "S,xvfsconf", "List of all configured filesystems");
2906 
2907 /*
2908  * Top level filesystem related information gathering.
2909  */
2910 static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
2911 
2912 static int
2913 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2914 {
2915 	int *name = (int *)arg1 - 1;	/* XXX */
2916 	u_int namelen = arg2 + 1;	/* XXX */
2917 	struct vfsconf *vfsp;
2918 	struct xvfsconf xvfsp;
2919 
2920 	printf("WARNING: userland calling deprecated sysctl, "
2921 	    "please rebuild world\n");
2922 
2923 #if 1 || defined(COMPAT_PRELITE2)
2924 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2925 	if (namelen == 1)
2926 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2927 #endif
2928 
2929 	switch (name[1]) {
2930 	case VFS_MAXTYPENUM:
2931 		if (namelen != 2)
2932 			return (ENOTDIR);
2933 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2934 	case VFS_CONF:
2935 		if (namelen != 3)
2936 			return (ENOTDIR);	/* overloaded */
2937 		for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next)
2938 			if (vfsp->vfc_typenum == name[2])
2939 				break;
2940 		if (vfsp == NULL)
2941 			return (EOPNOTSUPP);
2942 		vfsconf2x(vfsp, &xvfsp);
2943 		return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
2944 	}
2945 	return (EOPNOTSUPP);
2946 }
2947 
2948 SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP, vfs_sysctl,
2949 	"Generic filesystem");
2950 
2951 #if 1 || defined(COMPAT_PRELITE2)
2952 
2953 static int
2954 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2955 {
2956 	int error;
2957 	struct vfsconf *vfsp;
2958 	struct ovfsconf ovfs;
2959 
2960 	for (vfsp = vfsconf; vfsp; vfsp = vfsp->vfc_next) {
2961 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2962 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2963 		ovfs.vfc_index = vfsp->vfc_typenum;
2964 		ovfs.vfc_refcount = vfsp->vfc_refcount;
2965 		ovfs.vfc_flags = vfsp->vfc_flags;
2966 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2967 		if (error)
2968 			return error;
2969 	}
2970 	return 0;
2971 }
2972 
2973 #endif /* 1 || COMPAT_PRELITE2 */
2974 
2975 #define KINFO_VNODESLOP		10
2976 /*
2977  * Dump vnode list (via sysctl).
2978  */
2979 /* ARGSUSED */
2980 static int
2981 sysctl_vnode(SYSCTL_HANDLER_ARGS)
2982 {
2983 	struct xvnode *xvn;
2984 	struct thread *td = req->td;
2985 	struct mount *mp;
2986 	struct vnode *vp;
2987 	int error, len, n;
2988 
2989 	/*
2990 	 * Stale numvnodes access is not fatal here.
2991 	 */
2992 	req->lock = 0;
2993 	len = (numvnodes + KINFO_VNODESLOP) * sizeof *xvn;
2994 	if (!req->oldptr)
2995 		/* Make an estimate */
2996 		return (SYSCTL_OUT(req, 0, len));
2997 
2998 	sysctl_wire_old_buffer(req, 0);
2999 	xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3000 	n = 0;
3001 	mtx_lock(&mountlist_mtx);
3002 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3003 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx, td))
3004 			continue;
3005 		mtx_lock(&mntvnode_mtx);
3006 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3007 			if (n == len)
3008 				break;
3009 			vref(vp);
3010 			xvn[n].xv_size = sizeof *xvn;
3011 			xvn[n].xv_vnode = vp;
3012 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3013 			XV_COPY(usecount);
3014 			XV_COPY(writecount);
3015 			XV_COPY(holdcnt);
3016 			XV_COPY(id);
3017 			XV_COPY(mount);
3018 			XV_COPY(numoutput);
3019 			XV_COPY(type);
3020 #undef XV_COPY
3021 			xvn[n].xv_flag = vp->v_vflag;
3022 
3023 			switch (vp->v_type) {
3024 			case VREG:
3025 			case VDIR:
3026 			case VLNK:
3027 				xvn[n].xv_dev = vp->v_cachedfs;
3028 				xvn[n].xv_ino = vp->v_cachedid;
3029 				break;
3030 			case VBLK:
3031 			case VCHR:
3032 				if (vp->v_rdev == NULL) {
3033 					vrele(vp);
3034 					continue;
3035 				}
3036 				xvn[n].xv_dev = dev2udev(vp->v_rdev);
3037 				break;
3038 			case VSOCK:
3039 				xvn[n].xv_socket = vp->v_socket;
3040 				break;
3041 			case VFIFO:
3042 				xvn[n].xv_fifo = vp->v_fifoinfo;
3043 				break;
3044 			case VNON:
3045 			case VBAD:
3046 			default:
3047 				/* shouldn't happen? */
3048 				vrele(vp);
3049 				continue;
3050 			}
3051 			vrele(vp);
3052 			++n;
3053 		}
3054 		mtx_unlock(&mntvnode_mtx);
3055 		mtx_lock(&mountlist_mtx);
3056 		vfs_unbusy(mp, td);
3057 		if (n == len)
3058 			break;
3059 	}
3060 	mtx_unlock(&mountlist_mtx);
3061 
3062 	error = SYSCTL_OUT(req, xvn, n * sizeof *xvn);
3063 	free(xvn, M_TEMP);
3064 	return (error);
3065 }
3066 
3067 SYSCTL_PROC(_kern, KERN_VNODE, vnode, CTLTYPE_OPAQUE|CTLFLAG_RD,
3068 	0, 0, sysctl_vnode, "S,xvnode", "");
3069 
3070 /*
3071  * Check to see if a filesystem is mounted on a block device.
3072  */
3073 int
3074 vfs_mountedon(vp)
3075 	struct vnode *vp;
3076 {
3077 
3078 	if (vp->v_rdev->si_mountpoint != NULL)
3079 		return (EBUSY);
3080 	return (0);
3081 }
3082 
3083 /*
3084  * Unmount all filesystems. The list is traversed in reverse order
3085  * of mounting to avoid dependencies.
3086  */
3087 void
3088 vfs_unmountall()
3089 {
3090 	struct mount *mp;
3091 	struct thread *td;
3092 	int error;
3093 
3094 	if (curthread != NULL)
3095 		td = curthread;
3096 	else
3097 		td = FIRST_THREAD_IN_PROC(initproc); /* XXX XXX proc0? */
3098 	/*
3099 	 * Since this only runs when rebooting, it is not interlocked.
3100 	 */
3101 	while(!TAILQ_EMPTY(&mountlist)) {
3102 		mp = TAILQ_LAST(&mountlist, mntlist);
3103 		error = dounmount(mp, MNT_FORCE, td);
3104 		if (error) {
3105 			TAILQ_REMOVE(&mountlist, mp, mnt_list);
3106 			printf("unmount of %s failed (",
3107 			    mp->mnt_stat.f_mntonname);
3108 			if (error == EBUSY)
3109 				printf("BUSY)\n");
3110 			else
3111 				printf("%d)\n", error);
3112 		} else {
3113 			/* The unmount has removed mp from the mountlist */
3114 		}
3115 	}
3116 }
3117 
3118 /*
3119  * perform msync on all vnodes under a mount point
3120  * the mount point must be locked.
3121  */
3122 void
3123 vfs_msync(struct mount *mp, int flags)
3124 {
3125 	struct vnode *vp, *nvp;
3126 	struct vm_object *obj;
3127 	int tries;
3128 
3129 	GIANT_REQUIRED;
3130 
3131 	tries = 5;
3132 	mtx_lock(&mntvnode_mtx);
3133 loop:
3134 	for (vp = TAILQ_FIRST(&mp->mnt_nvnodelist); vp != NULL; vp = nvp) {
3135 		if (vp->v_mount != mp) {
3136 			if (--tries > 0)
3137 				goto loop;
3138 			break;
3139 		}
3140 		nvp = TAILQ_NEXT(vp, v_nmntvnodes);
3141 
3142 		VI_LOCK(vp);
3143 		if (vp->v_iflag & VI_XLOCK) {	/* XXX: what if MNT_WAIT? */
3144 			VI_UNLOCK(vp);
3145 			continue;
3146 		}
3147 
3148 		if ((vp->v_iflag & VI_OBJDIRTY) &&
3149 		    (flags == MNT_WAIT || VOP_ISLOCKED(vp, NULL) == 0)) {
3150 			mtx_unlock(&mntvnode_mtx);
3151 			if (!vget(vp,
3152 			    LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3153 			    curthread)) {
3154 				if (vp->v_vflag & VV_NOSYNC) {	/* unlinked */
3155 					vput(vp);
3156 					mtx_lock(&mntvnode_mtx);
3157 					continue;
3158 				}
3159 
3160 				if (VOP_GETVOBJECT(vp, &obj) == 0) {
3161 					vm_object_page_clean(obj, 0, 0,
3162 					    flags == MNT_WAIT ?
3163 					    OBJPC_SYNC : OBJPC_NOSYNC);
3164 				}
3165 				vput(vp);
3166 			}
3167 			mtx_lock(&mntvnode_mtx);
3168 			if (TAILQ_NEXT(vp, v_nmntvnodes) != nvp) {
3169 				if (--tries > 0)
3170 					goto loop;
3171 				break;
3172 			}
3173 		} else
3174 			VI_UNLOCK(vp);
3175 	}
3176 	mtx_unlock(&mntvnode_mtx);
3177 }
3178 
3179 /*
3180  * Create the VM object needed for VMIO and mmap support.  This
3181  * is done for all VREG files in the system.  Some filesystems might
3182  * afford the additional metadata buffering capability of the
3183  * VMIO code by making the device node be VMIO mode also.
3184  *
3185  * vp must be locked when vfs_object_create is called.
3186  */
3187 int
3188 vfs_object_create(vp, td, cred)
3189 	struct vnode *vp;
3190 	struct thread *td;
3191 	struct ucred *cred;
3192 {
3193 	GIANT_REQUIRED;
3194 	return (VOP_CREATEVOBJECT(vp, cred, td));
3195 }
3196 
3197 /*
3198  * Mark a vnode as free, putting it up for recycling.
3199  */
3200 void
3201 vfree(vp)
3202 	struct vnode *vp;
3203 {
3204 	int s;
3205 
3206 	ASSERT_VI_LOCKED(vp, "vfree");
3207 	s = splbio();
3208 	mtx_lock(&vnode_free_list_mtx);
3209 	KASSERT((vp->v_iflag & VI_FREE) == 0, ("vnode already free"));
3210 	if (vp->v_iflag & VI_AGE) {
3211 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
3212 	} else {
3213 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
3214 	}
3215 	freevnodes++;
3216 	mtx_unlock(&vnode_free_list_mtx);
3217 	vp->v_iflag &= ~VI_AGE;
3218 	vp->v_iflag |= VI_FREE;
3219 	splx(s);
3220 }
3221 
3222 /*
3223  * Opposite of vfree() - mark a vnode as in use.
3224  */
3225 void
3226 vbusy(vp)
3227 	struct vnode *vp;
3228 {
3229 	int s;
3230 
3231 	s = splbio();
3232 	ASSERT_VI_LOCKED(vp, "vbusy");
3233 	KASSERT((vp->v_iflag & VI_FREE) != 0, ("vnode not free"));
3234 
3235 	mtx_lock(&vnode_free_list_mtx);
3236 	TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
3237 	freevnodes--;
3238 	mtx_unlock(&vnode_free_list_mtx);
3239 
3240 	vp->v_iflag &= ~(VI_FREE|VI_AGE);
3241 	splx(s);
3242 }
3243 
3244 /*
3245  * Record a process's interest in events which might happen to
3246  * a vnode.  Because poll uses the historic select-style interface
3247  * internally, this routine serves as both the ``check for any
3248  * pending events'' and the ``record my interest in future events''
3249  * functions.  (These are done together, while the lock is held,
3250  * to avoid race conditions.)
3251  */
3252 int
3253 vn_pollrecord(vp, td, events)
3254 	struct vnode *vp;
3255 	struct thread *td;
3256 	short events;
3257 {
3258 
3259 	if (vp->v_pollinfo == NULL)
3260 		v_addpollinfo(vp);
3261 	mtx_lock(&vp->v_pollinfo->vpi_lock);
3262 	if (vp->v_pollinfo->vpi_revents & events) {
3263 		/*
3264 		 * This leaves events we are not interested
3265 		 * in available for the other process which
3266 		 * which presumably had requested them
3267 		 * (otherwise they would never have been
3268 		 * recorded).
3269 		 */
3270 		events &= vp->v_pollinfo->vpi_revents;
3271 		vp->v_pollinfo->vpi_revents &= ~events;
3272 
3273 		mtx_unlock(&vp->v_pollinfo->vpi_lock);
3274 		return events;
3275 	}
3276 	vp->v_pollinfo->vpi_events |= events;
3277 	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3278 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3279 	return 0;
3280 }
3281 
3282 /*
3283  * Note the occurrence of an event.  If the VN_POLLEVENT macro is used,
3284  * it is possible for us to miss an event due to race conditions, but
3285  * that condition is expected to be rare, so for the moment it is the
3286  * preferred interface.
3287  */
3288 void
3289 vn_pollevent(vp, events)
3290 	struct vnode *vp;
3291 	short events;
3292 {
3293 
3294 	if (vp->v_pollinfo == NULL)
3295 		v_addpollinfo(vp);
3296 	mtx_lock(&vp->v_pollinfo->vpi_lock);
3297 	if (vp->v_pollinfo->vpi_events & events) {
3298 		/*
3299 		 * We clear vpi_events so that we don't
3300 		 * call selwakeup() twice if two events are
3301 		 * posted before the polling process(es) is
3302 		 * awakened.  This also ensures that we take at
3303 		 * most one selwakeup() if the polling process
3304 		 * is no longer interested.  However, it does
3305 		 * mean that only one event can be noticed at
3306 		 * a time.  (Perhaps we should only clear those
3307 		 * event bits which we note?) XXX
3308 		 */
3309 		vp->v_pollinfo->vpi_events = 0;	/* &= ~events ??? */
3310 		vp->v_pollinfo->vpi_revents |= events;
3311 		selwakeup(&vp->v_pollinfo->vpi_selinfo);
3312 	}
3313 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3314 }
3315 
3316 /*
3317  * Wake up anyone polling on vp because it is being revoked.
3318  * This depends on dead_poll() returning POLLHUP for correct
3319  * behavior.
3320  */
3321 void
3322 vn_pollgone(vp)
3323 	struct vnode *vp;
3324 {
3325 
3326 	mtx_lock(&vp->v_pollinfo->vpi_lock);
3327 	VN_KNOTE(vp, NOTE_REVOKE);
3328 	if (vp->v_pollinfo->vpi_events) {
3329 		vp->v_pollinfo->vpi_events = 0;
3330 		selwakeup(&vp->v_pollinfo->vpi_selinfo);
3331 	}
3332 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3333 }
3334 
3335 
3336 
3337 /*
3338  * Routine to create and manage a filesystem syncer vnode.
3339  */
3340 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
3341 static int	sync_fsync(struct  vop_fsync_args *);
3342 static int	sync_inactive(struct  vop_inactive_args *);
3343 static int	sync_reclaim(struct  vop_reclaim_args *);
3344 static int	sync_print(struct vop_print_args *);
3345 
3346 static vop_t **sync_vnodeop_p;
3347 static struct vnodeopv_entry_desc sync_vnodeop_entries[] = {
3348 	{ &vop_default_desc,	(vop_t *) vop_eopnotsupp },
3349 	{ &vop_close_desc,	(vop_t *) sync_close },		/* close */
3350 	{ &vop_fsync_desc,	(vop_t *) sync_fsync },		/* fsync */
3351 	{ &vop_inactive_desc,	(vop_t *) sync_inactive },	/* inactive */
3352 	{ &vop_reclaim_desc,	(vop_t *) sync_reclaim },	/* reclaim */
3353 	{ &vop_lock_desc,	(vop_t *) vop_stdlock },	/* lock */
3354 	{ &vop_unlock_desc,	(vop_t *) vop_stdunlock },	/* unlock */
3355 	{ &vop_print_desc,	(vop_t *) sync_print },		/* print */
3356 	{ &vop_islocked_desc,	(vop_t *) vop_stdislocked },	/* islocked */
3357 	{ NULL, NULL }
3358 };
3359 static struct vnodeopv_desc sync_vnodeop_opv_desc =
3360 	{ &sync_vnodeop_p, sync_vnodeop_entries };
3361 
3362 VNODEOP_SET(sync_vnodeop_opv_desc);
3363 
3364 /*
3365  * Create a new filesystem syncer vnode for the specified mount point.
3366  */
3367 int
3368 vfs_allocate_syncvnode(mp)
3369 	struct mount *mp;
3370 {
3371 	struct vnode *vp;
3372 	static long start, incr, next;
3373 	int error;
3374 
3375 	/* Allocate a new vnode */
3376 	if ((error = getnewvnode("vfs", mp, sync_vnodeop_p, &vp)) != 0) {
3377 		mp->mnt_syncer = NULL;
3378 		return (error);
3379 	}
3380 	vp->v_type = VNON;
3381 	/*
3382 	 * Place the vnode onto the syncer worklist. We attempt to
3383 	 * scatter them about on the list so that they will go off
3384 	 * at evenly distributed times even if all the filesystems
3385 	 * are mounted at once.
3386 	 */
3387 	next += incr;
3388 	if (next == 0 || next > syncer_maxdelay) {
3389 		start /= 2;
3390 		incr /= 2;
3391 		if (start == 0) {
3392 			start = syncer_maxdelay / 2;
3393 			incr = syncer_maxdelay;
3394 		}
3395 		next = start;
3396 	}
3397 	VI_LOCK(vp);
3398 	vn_syncer_add_to_worklist(vp, syncdelay > 0 ? next % syncdelay : 0);
3399 	VI_UNLOCK(vp);
3400 	mp->mnt_syncer = vp;
3401 	return (0);
3402 }
3403 
3404 /*
3405  * Do a lazy sync of the filesystem.
3406  */
3407 static int
3408 sync_fsync(ap)
3409 	struct vop_fsync_args /* {
3410 		struct vnode *a_vp;
3411 		struct ucred *a_cred;
3412 		int a_waitfor;
3413 		struct thread *a_td;
3414 	} */ *ap;
3415 {
3416 	struct vnode *syncvp = ap->a_vp;
3417 	struct mount *mp = syncvp->v_mount;
3418 	struct thread *td = ap->a_td;
3419 	int asyncflag;
3420 
3421 	/*
3422 	 * We only need to do something if this is a lazy evaluation.
3423 	 */
3424 	if (ap->a_waitfor != MNT_LAZY)
3425 		return (0);
3426 
3427 	/*
3428 	 * Move ourselves to the back of the sync list.
3429 	 */
3430 	VI_LOCK(syncvp);
3431 	vn_syncer_add_to_worklist(syncvp, syncdelay);
3432 	VI_UNLOCK(syncvp);
3433 
3434 	/*
3435 	 * Walk the list of vnodes pushing all that are dirty and
3436 	 * not already on the sync list.
3437 	 */
3438 	mtx_lock(&mountlist_mtx);
3439 	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_mtx, td) != 0) {
3440 		mtx_unlock(&mountlist_mtx);
3441 		return (0);
3442 	}
3443 	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3444 		vfs_unbusy(mp, td);
3445 		return (0);
3446 	}
3447 	asyncflag = mp->mnt_flag & MNT_ASYNC;
3448 	mp->mnt_flag &= ~MNT_ASYNC;
3449 	vfs_msync(mp, MNT_NOWAIT);
3450 	VFS_SYNC(mp, MNT_LAZY, ap->a_cred, td);
3451 	if (asyncflag)
3452 		mp->mnt_flag |= MNT_ASYNC;
3453 	vn_finished_write(mp);
3454 	vfs_unbusy(mp, td);
3455 	return (0);
3456 }
3457 
3458 /*
3459  * The syncer vnode is no referenced.
3460  */
3461 static int
3462 sync_inactive(ap)
3463 	struct vop_inactive_args /* {
3464 		struct vnode *a_vp;
3465 		struct thread *a_td;
3466 	} */ *ap;
3467 {
3468 
3469 	VOP_UNLOCK(ap->a_vp, 0, ap->a_td);
3470 	vgone(ap->a_vp);
3471 	return (0);
3472 }
3473 
3474 /*
3475  * The syncer vnode is no longer needed and is being decommissioned.
3476  *
3477  * Modifications to the worklist must be protected at splbio().
3478  */
3479 static int
3480 sync_reclaim(ap)
3481 	struct vop_reclaim_args /* {
3482 		struct vnode *a_vp;
3483 	} */ *ap;
3484 {
3485 	struct vnode *vp = ap->a_vp;
3486 	int s;
3487 
3488 	s = splbio();
3489 	vp->v_mount->mnt_syncer = NULL;
3490 	VI_LOCK(vp);
3491 	if (vp->v_iflag & VI_ONWORKLST) {
3492 		mtx_lock(&sync_mtx);
3493 		LIST_REMOVE(vp, v_synclist);
3494 		mtx_unlock(&sync_mtx);
3495 		vp->v_iflag &= ~VI_ONWORKLST;
3496 	}
3497 	VI_UNLOCK(vp);
3498 	splx(s);
3499 
3500 	return (0);
3501 }
3502 
3503 /*
3504  * Print out a syncer vnode.
3505  */
3506 static int
3507 sync_print(ap)
3508 	struct vop_print_args /* {
3509 		struct vnode *a_vp;
3510 	} */ *ap;
3511 {
3512 	struct vnode *vp = ap->a_vp;
3513 
3514 	printf("syncer vnode");
3515 	if (vp->v_vnlock != NULL)
3516 		lockmgr_printinfo(vp->v_vnlock);
3517 	printf("\n");
3518 	return (0);
3519 }
3520 
3521 /*
3522  * extract the dev_t from a VCHR
3523  */
3524 dev_t
3525 vn_todev(vp)
3526 	struct vnode *vp;
3527 {
3528 	if (vp->v_type != VCHR)
3529 		return (NODEV);
3530 	return (vp->v_rdev);
3531 }
3532 
3533 /*
3534  * Check if vnode represents a disk device
3535  */
3536 int
3537 vn_isdisk(vp, errp)
3538 	struct vnode *vp;
3539 	int *errp;
3540 {
3541 	struct cdevsw *cdevsw;
3542 
3543 	if (vp->v_type != VCHR) {
3544 		if (errp != NULL)
3545 			*errp = ENOTBLK;
3546 		return (0);
3547 	}
3548 	if (vp->v_rdev == NULL) {
3549 		if (errp != NULL)
3550 			*errp = ENXIO;
3551 		return (0);
3552 	}
3553 	cdevsw = devsw(vp->v_rdev);
3554 	if (cdevsw == NULL) {
3555 		if (errp != NULL)
3556 			*errp = ENXIO;
3557 		return (0);
3558 	}
3559 	if (!(cdevsw->d_flags & D_DISK)) {
3560 		if (errp != NULL)
3561 			*errp = ENOTBLK;
3562 		return (0);
3563 	}
3564 	if (errp != NULL)
3565 		*errp = 0;
3566 	return (1);
3567 }
3568 
3569 /*
3570  * Free data allocated by namei(); see namei(9) for details.
3571  */
3572 void
3573 NDFREE(ndp, flags)
3574      struct nameidata *ndp;
3575      const uint flags;
3576 {
3577 	if (!(flags & NDF_NO_FREE_PNBUF) &&
3578 	    (ndp->ni_cnd.cn_flags & HASBUF)) {
3579 		uma_zfree(namei_zone, ndp->ni_cnd.cn_pnbuf);
3580 		ndp->ni_cnd.cn_flags &= ~HASBUF;
3581 	}
3582 	if (!(flags & NDF_NO_DVP_UNLOCK) &&
3583 	    (ndp->ni_cnd.cn_flags & LOCKPARENT) &&
3584 	    ndp->ni_dvp != ndp->ni_vp)
3585 		VOP_UNLOCK(ndp->ni_dvp, 0, ndp->ni_cnd.cn_thread);
3586 	if (!(flags & NDF_NO_DVP_RELE) &&
3587 	    (ndp->ni_cnd.cn_flags & (LOCKPARENT|WANTPARENT))) {
3588 		vrele(ndp->ni_dvp);
3589 		ndp->ni_dvp = NULL;
3590 	}
3591 	if (!(flags & NDF_NO_VP_UNLOCK) &&
3592 	    (ndp->ni_cnd.cn_flags & LOCKLEAF) && ndp->ni_vp)
3593 		VOP_UNLOCK(ndp->ni_vp, 0, ndp->ni_cnd.cn_thread);
3594 	if (!(flags & NDF_NO_VP_RELE) &&
3595 	    ndp->ni_vp) {
3596 		vrele(ndp->ni_vp);
3597 		ndp->ni_vp = NULL;
3598 	}
3599 	if (!(flags & NDF_NO_STARTDIR_RELE) &&
3600 	    (ndp->ni_cnd.cn_flags & SAVESTART)) {
3601 		vrele(ndp->ni_startdir);
3602 		ndp->ni_startdir = NULL;
3603 	}
3604 }
3605 
3606 /*
3607  * Common filesystem object access control check routine.  Accepts a
3608  * vnode's type, "mode", uid and gid, requested access mode, credentials,
3609  * and optional call-by-reference privused argument allowing vaccess()
3610  * to indicate to the caller whether privilege was used to satisfy the
3611  * request (obsoleted).  Returns 0 on success, or an errno on failure.
3612  */
3613 int
3614 vaccess(type, file_mode, file_uid, file_gid, acc_mode, cred, privused)
3615 	enum vtype type;
3616 	mode_t file_mode;
3617 	uid_t file_uid;
3618 	gid_t file_gid;
3619 	mode_t acc_mode;
3620 	struct ucred *cred;
3621 	int *privused;
3622 {
3623 	mode_t dac_granted;
3624 #ifdef CAPABILITIES
3625 	mode_t cap_granted;
3626 #endif
3627 
3628 	/*
3629 	 * Look for a normal, non-privileged way to access the file/directory
3630 	 * as requested.  If it exists, go with that.
3631 	 */
3632 
3633 	if (privused != NULL)
3634 		*privused = 0;
3635 
3636 	dac_granted = 0;
3637 
3638 	/* Check the owner. */
3639 	if (cred->cr_uid == file_uid) {
3640 		dac_granted |= VADMIN;
3641 		if (file_mode & S_IXUSR)
3642 			dac_granted |= VEXEC;
3643 		if (file_mode & S_IRUSR)
3644 			dac_granted |= VREAD;
3645 		if (file_mode & S_IWUSR)
3646 			dac_granted |= (VWRITE | VAPPEND);
3647 
3648 		if ((acc_mode & dac_granted) == acc_mode)
3649 			return (0);
3650 
3651 		goto privcheck;
3652 	}
3653 
3654 	/* Otherwise, check the groups (first match) */
3655 	if (groupmember(file_gid, cred)) {
3656 		if (file_mode & S_IXGRP)
3657 			dac_granted |= VEXEC;
3658 		if (file_mode & S_IRGRP)
3659 			dac_granted |= VREAD;
3660 		if (file_mode & S_IWGRP)
3661 			dac_granted |= (VWRITE | VAPPEND);
3662 
3663 		if ((acc_mode & dac_granted) == acc_mode)
3664 			return (0);
3665 
3666 		goto privcheck;
3667 	}
3668 
3669 	/* Otherwise, check everyone else. */
3670 	if (file_mode & S_IXOTH)
3671 		dac_granted |= VEXEC;
3672 	if (file_mode & S_IROTH)
3673 		dac_granted |= VREAD;
3674 	if (file_mode & S_IWOTH)
3675 		dac_granted |= (VWRITE | VAPPEND);
3676 	if ((acc_mode & dac_granted) == acc_mode)
3677 		return (0);
3678 
3679 privcheck:
3680 	if (!suser_cred(cred, PRISON_ROOT)) {
3681 		/* XXX audit: privilege used */
3682 		if (privused != NULL)
3683 			*privused = 1;
3684 		return (0);
3685 	}
3686 
3687 #ifdef CAPABILITIES
3688 	/*
3689 	 * Build a capability mask to determine if the set of capabilities
3690 	 * satisfies the requirements when combined with the granted mask
3691 	 * from above.
3692 	 * For each capability, if the capability is required, bitwise
3693 	 * or the request type onto the cap_granted mask.
3694 	 */
3695 	cap_granted = 0;
3696 
3697 	if (type == VDIR) {
3698 		/*
3699 		 * For directories, use CAP_DAC_READ_SEARCH to satisfy
3700 		 * VEXEC requests, instead of CAP_DAC_EXECUTE.
3701 		 */
3702 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3703 		    !cap_check(cred, NULL, CAP_DAC_READ_SEARCH, PRISON_ROOT))
3704 			cap_granted |= VEXEC;
3705 	} else {
3706 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3707 		    !cap_check(cred, NULL, CAP_DAC_EXECUTE, PRISON_ROOT))
3708 			cap_granted |= VEXEC;
3709 	}
3710 
3711 	if ((acc_mode & VREAD) && ((dac_granted & VREAD) == 0) &&
3712 	    !cap_check(cred, NULL, CAP_DAC_READ_SEARCH, PRISON_ROOT))
3713 		cap_granted |= VREAD;
3714 
3715 	if ((acc_mode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3716 	    !cap_check(cred, NULL, CAP_DAC_WRITE, PRISON_ROOT))
3717 		cap_granted |= (VWRITE | VAPPEND);
3718 
3719 	if ((acc_mode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3720 	    !cap_check(cred, NULL, CAP_FOWNER, PRISON_ROOT))
3721 		cap_granted |= VADMIN;
3722 
3723 	if ((acc_mode & (cap_granted | dac_granted)) == acc_mode) {
3724 		/* XXX audit: privilege used */
3725 		if (privused != NULL)
3726 			*privused = 1;
3727 		return (0);
3728 	}
3729 #endif
3730 
3731 	return ((acc_mode & VADMIN) ? EPERM : EACCES);
3732 }
3733 
3734 /*
3735  * Credential check based on process requesting service, and per-attribute
3736  * permissions.
3737  */
3738 int
3739 extattr_check_cred(struct vnode *vp, int attrnamespace,
3740     struct ucred *cred, struct thread *td, int access)
3741 {
3742 
3743 	/*
3744 	 * Kernel-invoked always succeeds.
3745 	 */
3746 	if (cred == NOCRED)
3747 		return (0);
3748 
3749 	/*
3750 	 * Do not allow privileged processes in jail to directly
3751 	 * manipulate system attributes.
3752 	 *
3753 	 * XXX What capability should apply here?
3754 	 * Probably CAP_SYS_SETFFLAG.
3755 	 */
3756 	switch (attrnamespace) {
3757 	case EXTATTR_NAMESPACE_SYSTEM:
3758 		/* Potentially should be: return (EPERM); */
3759 		return (suser_cred(cred, 0));
3760 	case EXTATTR_NAMESPACE_USER:
3761 		return (VOP_ACCESS(vp, access, cred, td));
3762 	default:
3763 		return (EPERM);
3764 	}
3765 }
3766