xref: /freebsd/sys/kern/vfs_subr.c (revision 4a5216a6dc0c3ce4cf5f2d3ee8af0c3ff3402c4f)
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  * 4. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  *	@(#)vfs_subr.c	8.31 (Berkeley) 5/26/95
35  */
36 
37 /*
38  * External virtual filesystem routines
39  */
40 
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include "opt_ddb.h"
45 #include "opt_mac.h"
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/bio.h>
50 #include <sys/buf.h>
51 #include <sys/condvar.h>
52 #include <sys/conf.h>
53 #include <sys/dirent.h>
54 #include <sys/event.h>
55 #include <sys/eventhandler.h>
56 #include <sys/extattr.h>
57 #include <sys/file.h>
58 #include <sys/fcntl.h>
59 #include <sys/jail.h>
60 #include <sys/kdb.h>
61 #include <sys/kernel.h>
62 #include <sys/kthread.h>
63 #include <sys/lockf.h>
64 #include <sys/malloc.h>
65 #include <sys/mount.h>
66 #include <sys/namei.h>
67 #include <sys/priv.h>
68 #include <sys/reboot.h>
69 #include <sys/sleepqueue.h>
70 #include <sys/stat.h>
71 #include <sys/sysctl.h>
72 #include <sys/syslog.h>
73 #include <sys/vmmeter.h>
74 #include <sys/vnode.h>
75 
76 #include <machine/stdarg.h>
77 
78 #include <security/mac/mac_framework.h>
79 
80 #include <vm/vm.h>
81 #include <vm/vm_object.h>
82 #include <vm/vm_extern.h>
83 #include <vm/pmap.h>
84 #include <vm/vm_map.h>
85 #include <vm/vm_page.h>
86 #include <vm/vm_kern.h>
87 #include <vm/uma.h>
88 
89 #ifdef DDB
90 #include <ddb/ddb.h>
91 #endif
92 
93 #define	WI_MPSAFEQ	0
94 #define	WI_GIANTQ	1
95 
96 static MALLOC_DEFINE(M_NETADDR, "subr_export_host", "Export host address structure");
97 
98 static void	delmntque(struct vnode *vp);
99 static int	flushbuflist(struct bufv *bufv, int flags, struct bufobj *bo,
100 		    int slpflag, int slptimeo);
101 static void	syncer_shutdown(void *arg, int howto);
102 static int	vtryrecycle(struct vnode *vp);
103 static void	vbusy(struct vnode *vp);
104 static void	vinactive(struct vnode *, struct thread *);
105 static void	v_incr_usecount(struct vnode *);
106 static void	v_decr_usecount(struct vnode *);
107 static void	v_decr_useonly(struct vnode *);
108 static void	v_upgrade_usecount(struct vnode *);
109 static void	vfree(struct vnode *);
110 static void	vnlru_free(int);
111 static void	vdestroy(struct vnode *);
112 static void	vgonel(struct vnode *);
113 static void	vfs_knllock(void *arg);
114 static void	vfs_knlunlock(void *arg);
115 static int	vfs_knllocked(void *arg);
116 
117 
118 /*
119  * Enable Giant pushdown based on whether or not the vm is mpsafe in this
120  * build.  Without mpsafevm the buffer cache can not run Giant free.
121  */
122 int mpsafe_vfs = 1;
123 TUNABLE_INT("debug.mpsafevfs", &mpsafe_vfs);
124 SYSCTL_INT(_debug, OID_AUTO, mpsafevfs, CTLFLAG_RD, &mpsafe_vfs, 0,
125     "MPSAFE VFS");
126 
127 /*
128  * Number of vnodes in existence.  Increased whenever getnewvnode()
129  * allocates a new vnode, decreased on vdestroy() called on VI_DOOMed
130  * vnode.
131  */
132 static unsigned long	numvnodes;
133 
134 SYSCTL_LONG(_vfs, OID_AUTO, numvnodes, CTLFLAG_RD, &numvnodes, 0, "");
135 
136 /*
137  * Conversion tables for conversion from vnode types to inode formats
138  * and back.
139  */
140 enum vtype iftovt_tab[16] = {
141 	VNON, VFIFO, VCHR, VNON, VDIR, VNON, VBLK, VNON,
142 	VREG, VNON, VLNK, VNON, VSOCK, VNON, VNON, VBAD,
143 };
144 int vttoif_tab[10] = {
145 	0, S_IFREG, S_IFDIR, S_IFBLK, S_IFCHR, S_IFLNK,
146 	S_IFSOCK, S_IFIFO, S_IFMT, S_IFMT
147 };
148 
149 /*
150  * List of vnodes that are ready for recycling.
151  */
152 static TAILQ_HEAD(freelst, vnode) vnode_free_list;
153 
154 /*
155  * Free vnode target.  Free vnodes may simply be files which have been stat'd
156  * but not read.  This is somewhat common, and a small cache of such files
157  * should be kept to avoid recreation costs.
158  */
159 static u_long wantfreevnodes;
160 SYSCTL_LONG(_vfs, OID_AUTO, wantfreevnodes, CTLFLAG_RW, &wantfreevnodes, 0, "");
161 /* Number of vnodes in the free list. */
162 static u_long freevnodes;
163 SYSCTL_LONG(_vfs, OID_AUTO, freevnodes, CTLFLAG_RD, &freevnodes, 0, "");
164 
165 /*
166  * Various variables used for debugging the new implementation of
167  * reassignbuf().
168  * XXX these are probably of (very) limited utility now.
169  */
170 static int reassignbufcalls;
171 SYSCTL_INT(_vfs, OID_AUTO, reassignbufcalls, CTLFLAG_RW, &reassignbufcalls, 0, "");
172 
173 /*
174  * Cache for the mount type id assigned to NFS.  This is used for
175  * special checks in nfs/nfs_nqlease.c and vm/vnode_pager.c.
176  */
177 int	nfs_mount_type = -1;
178 
179 /* To keep more than one thread at a time from running vfs_getnewfsid */
180 static struct mtx mntid_mtx;
181 
182 /*
183  * Lock for any access to the following:
184  *	vnode_free_list
185  *	numvnodes
186  *	freevnodes
187  */
188 static struct mtx vnode_free_list_mtx;
189 
190 /* Publicly exported FS */
191 struct nfs_public nfs_pub;
192 
193 /* Zone for allocation of new vnodes - used exclusively by getnewvnode() */
194 static uma_zone_t vnode_zone;
195 static uma_zone_t vnodepoll_zone;
196 
197 /* Set to 1 to print out reclaim of active vnodes */
198 int	prtactive;
199 
200 /*
201  * The workitem queue.
202  *
203  * It is useful to delay writes of file data and filesystem metadata
204  * for tens of seconds so that quickly created and deleted files need
205  * not waste disk bandwidth being created and removed. To realize this,
206  * we append vnodes to a "workitem" queue. When running with a soft
207  * updates implementation, most pending metadata dependencies should
208  * not wait for more than a few seconds. Thus, mounted on block devices
209  * are delayed only about a half the time that file data is delayed.
210  * Similarly, directory updates are more critical, so are only delayed
211  * about a third the time that file data is delayed. Thus, there are
212  * SYNCER_MAXDELAY queues that are processed round-robin at a rate of
213  * one each second (driven off the filesystem syncer process). The
214  * syncer_delayno variable indicates the next queue that is to be processed.
215  * Items that need to be processed soon are placed in this queue:
216  *
217  *	syncer_workitem_pending[syncer_delayno]
218  *
219  * A delay of fifteen seconds is done by placing the request fifteen
220  * entries later in the queue:
221  *
222  *	syncer_workitem_pending[(syncer_delayno + 15) & syncer_mask]
223  *
224  */
225 static int syncer_delayno;
226 static long syncer_mask;
227 LIST_HEAD(synclist, bufobj);
228 static struct synclist *syncer_workitem_pending[2];
229 /*
230  * The sync_mtx protects:
231  *	bo->bo_synclist
232  *	sync_vnode_count
233  *	syncer_delayno
234  *	syncer_state
235  *	syncer_workitem_pending
236  *	syncer_worklist_len
237  *	rushjob
238  */
239 static struct mtx sync_mtx;
240 static struct cv sync_wakeup;
241 
242 #define SYNCER_MAXDELAY		32
243 static int syncer_maxdelay = SYNCER_MAXDELAY;	/* maximum delay time */
244 static int syncdelay = 30;		/* max time to delay syncing data */
245 static int filedelay = 30;		/* time to delay syncing files */
246 SYSCTL_INT(_kern, OID_AUTO, filedelay, CTLFLAG_RW, &filedelay, 0, "");
247 static int dirdelay = 29;		/* time to delay syncing directories */
248 SYSCTL_INT(_kern, OID_AUTO, dirdelay, CTLFLAG_RW, &dirdelay, 0, "");
249 static int metadelay = 28;		/* time to delay syncing metadata */
250 SYSCTL_INT(_kern, OID_AUTO, metadelay, CTLFLAG_RW, &metadelay, 0, "");
251 static int rushjob;		/* number of slots to run ASAP */
252 static int stat_rush_requests;	/* number of times I/O speeded up */
253 SYSCTL_INT(_debug, OID_AUTO, rush_requests, CTLFLAG_RW, &stat_rush_requests, 0, "");
254 
255 /*
256  * When shutting down the syncer, run it at four times normal speed.
257  */
258 #define SYNCER_SHUTDOWN_SPEEDUP		4
259 static int sync_vnode_count;
260 static int syncer_worklist_len;
261 static enum { SYNCER_RUNNING, SYNCER_SHUTTING_DOWN, SYNCER_FINAL_DELAY }
262     syncer_state;
263 
264 /*
265  * Number of vnodes we want to exist at any one time.  This is mostly used
266  * to size hash tables in vnode-related code.  It is normally not used in
267  * getnewvnode(), as wantfreevnodes is normally nonzero.)
268  *
269  * XXX desiredvnodes is historical cruft and should not exist.
270  */
271 int desiredvnodes;
272 SYSCTL_INT(_kern, KERN_MAXVNODES, maxvnodes, CTLFLAG_RW,
273     &desiredvnodes, 0, "Maximum number of vnodes");
274 SYSCTL_INT(_kern, OID_AUTO, minvnodes, CTLFLAG_RW,
275     &wantfreevnodes, 0, "Minimum number of vnodes (legacy)");
276 static int vnlru_nowhere;
277 SYSCTL_INT(_debug, OID_AUTO, vnlru_nowhere, CTLFLAG_RW,
278     &vnlru_nowhere, 0, "Number of times the vnlru process ran without success");
279 
280 /*
281  * Macros to control when a vnode is freed and recycled.  All require
282  * the vnode interlock.
283  */
284 #define VCANRECYCLE(vp) (((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
285 #define VSHOULDFREE(vp) (!((vp)->v_iflag & VI_FREE) && !(vp)->v_holdcnt)
286 #define VSHOULDBUSY(vp) (((vp)->v_iflag & VI_FREE) && (vp)->v_holdcnt)
287 
288 
289 /*
290  * Initialize the vnode management data structures.
291  */
292 #ifndef	MAXVNODES_MAX
293 #define	MAXVNODES_MAX	100000
294 #endif
295 static void
296 vntblinit(void *dummy __unused)
297 {
298 
299 	/*
300 	 * Desiredvnodes is a function of the physical memory size and
301 	 * the kernel's heap size.  Specifically, desiredvnodes scales
302 	 * in proportion to the physical memory size until two fifths
303 	 * of the kernel's heap size is consumed by vnodes and vm
304 	 * objects.
305 	 */
306 	desiredvnodes = min(maxproc + cnt.v_page_count / 4, 2 * vm_kmem_size /
307 	    (5 * (sizeof(struct vm_object) + sizeof(struct vnode))));
308 	if (desiredvnodes > MAXVNODES_MAX) {
309 		if (bootverbose)
310 			printf("Reducing kern.maxvnodes %d -> %d\n",
311 			    desiredvnodes, MAXVNODES_MAX);
312 		desiredvnodes = MAXVNODES_MAX;
313 	}
314 	wantfreevnodes = desiredvnodes / 4;
315 	mtx_init(&mntid_mtx, "mntid", NULL, MTX_DEF);
316 	TAILQ_INIT(&vnode_free_list);
317 	mtx_init(&vnode_free_list_mtx, "vnode_free_list", NULL, MTX_DEF);
318 	vnode_zone = uma_zcreate("VNODE", sizeof (struct vnode), NULL, NULL,
319 	    NULL, NULL, UMA_ALIGN_PTR, 0);
320 	vnodepoll_zone = uma_zcreate("VNODEPOLL", sizeof (struct vpollinfo),
321 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
322 	/*
323 	 * Initialize the filesystem syncer.
324 	 */
325 	syncer_workitem_pending[WI_MPSAFEQ] = hashinit(syncer_maxdelay, M_VNODE,
326 	    &syncer_mask);
327 	syncer_workitem_pending[WI_GIANTQ] = hashinit(syncer_maxdelay, M_VNODE,
328 	    &syncer_mask);
329 	syncer_maxdelay = syncer_mask + 1;
330 	mtx_init(&sync_mtx, "Syncer mtx", NULL, MTX_DEF);
331 	cv_init(&sync_wakeup, "syncer");
332 }
333 SYSINIT(vfs, SI_SUB_VFS, SI_ORDER_FIRST, vntblinit, NULL);
334 
335 
336 /*
337  * Mark a mount point as busy. Used to synchronize access and to delay
338  * unmounting. Interlock is not released on failure.
339  */
340 int
341 vfs_busy(struct mount *mp, int flags, struct mtx *interlkp)
342 {
343 	int lkflags;
344 
345 	MNT_ILOCK(mp);
346 	MNT_REF(mp);
347 	if (mp->mnt_kern_flag & MNTK_UNMOUNT) {
348 		if (flags & LK_NOWAIT) {
349 			MNT_REL(mp);
350 			MNT_IUNLOCK(mp);
351 			return (ENOENT);
352 		}
353 		if (interlkp)
354 			mtx_unlock(interlkp);
355 		mp->mnt_kern_flag |= MNTK_MWAIT;
356 		/*
357 		 * Since all busy locks are shared except the exclusive
358 		 * lock granted when unmounting, the only place that a
359 		 * wakeup needs to be done is at the release of the
360 		 * exclusive lock at the end of dounmount.
361 		 */
362 		msleep(mp, MNT_MTX(mp), PVFS, "vfs_busy", 0);
363 		MNT_REL(mp);
364 		MNT_IUNLOCK(mp);
365 		if (interlkp)
366 			mtx_lock(interlkp);
367 		return (ENOENT);
368 	}
369 	if (interlkp)
370 		mtx_unlock(interlkp);
371 	lkflags = LK_SHARED | LK_INTERLOCK;
372 	if (lockmgr(&mp->mnt_lock, lkflags, MNT_MTX(mp)))
373 		panic("vfs_busy: unexpected lock failure");
374 	return (0);
375 }
376 
377 /*
378  * Free a busy filesystem.
379  */
380 void
381 vfs_unbusy(struct mount *mp)
382 {
383 
384 	lockmgr(&mp->mnt_lock, LK_RELEASE, NULL);
385 	vfs_rel(mp);
386 }
387 
388 /*
389  * Lookup a mount point by filesystem identifier.
390  */
391 struct mount *
392 vfs_getvfs(fsid_t *fsid)
393 {
394 	struct mount *mp;
395 
396 	mtx_lock(&mountlist_mtx);
397 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
398 		if (mp->mnt_stat.f_fsid.val[0] == fsid->val[0] &&
399 		    mp->mnt_stat.f_fsid.val[1] == fsid->val[1]) {
400 			vfs_ref(mp);
401 			mtx_unlock(&mountlist_mtx);
402 			return (mp);
403 		}
404 	}
405 	mtx_unlock(&mountlist_mtx);
406 	return ((struct mount *) 0);
407 }
408 
409 /*
410  * Check if a user can access privileged mount options.
411  */
412 int
413 vfs_suser(struct mount *mp, struct thread *td)
414 {
415 	int error;
416 
417 	/*
418 	 * If the thread is jailed, but this is not a jail-friendly file
419 	 * system, deny immediately.
420 	 */
421 	if (jailed(td->td_ucred) && !(mp->mnt_vfc->vfc_flags & VFCF_JAIL))
422 		return (EPERM);
423 
424 	/*
425 	 * If the file system was mounted outside a jail and a jailed thread
426 	 * tries to access it, deny immediately.
427 	 */
428 	if (!jailed(mp->mnt_cred) && jailed(td->td_ucred))
429 		return (EPERM);
430 
431 	/*
432 	 * If the file system was mounted inside different jail that the jail of
433 	 * the calling thread, deny immediately.
434 	 */
435 	if (jailed(mp->mnt_cred) && jailed(td->td_ucred) &&
436 	    mp->mnt_cred->cr_prison != td->td_ucred->cr_prison) {
437 		return (EPERM);
438 	}
439 
440 	if ((mp->mnt_flag & MNT_USER) == 0 ||
441 	    mp->mnt_cred->cr_uid != td->td_ucred->cr_uid) {
442 		if ((error = priv_check(td, PRIV_VFS_MOUNT_OWNER)) != 0)
443 			return (error);
444 	}
445 	return (0);
446 }
447 
448 /*
449  * Get a new unique fsid.  Try to make its val[0] unique, since this value
450  * will be used to create fake device numbers for stat().  Also try (but
451  * not so hard) make its val[0] unique mod 2^16, since some emulators only
452  * support 16-bit device numbers.  We end up with unique val[0]'s for the
453  * first 2^16 calls and unique val[0]'s mod 2^16 for the first 2^8 calls.
454  *
455  * Keep in mind that several mounts may be running in parallel.  Starting
456  * the search one past where the previous search terminated is both a
457  * micro-optimization and a defense against returning the same fsid to
458  * different mounts.
459  */
460 void
461 vfs_getnewfsid(struct mount *mp)
462 {
463 	static u_int16_t mntid_base;
464 	struct mount *nmp;
465 	fsid_t tfsid;
466 	int mtype;
467 
468 	mtx_lock(&mntid_mtx);
469 	mtype = mp->mnt_vfc->vfc_typenum;
470 	tfsid.val[1] = mtype;
471 	mtype = (mtype & 0xFF) << 24;
472 	for (;;) {
473 		tfsid.val[0] = makedev(255,
474 		    mtype | ((mntid_base & 0xFF00) << 8) | (mntid_base & 0xFF));
475 		mntid_base++;
476 		if ((nmp = vfs_getvfs(&tfsid)) == NULL)
477 			break;
478 		vfs_rel(nmp);
479 	}
480 	mp->mnt_stat.f_fsid.val[0] = tfsid.val[0];
481 	mp->mnt_stat.f_fsid.val[1] = tfsid.val[1];
482 	mtx_unlock(&mntid_mtx);
483 }
484 
485 /*
486  * Knob to control the precision of file timestamps:
487  *
488  *   0 = seconds only; nanoseconds zeroed.
489  *   1 = seconds and nanoseconds, accurate within 1/HZ.
490  *   2 = seconds and nanoseconds, truncated to microseconds.
491  * >=3 = seconds and nanoseconds, maximum precision.
492  */
493 enum { TSP_SEC, TSP_HZ, TSP_USEC, TSP_NSEC };
494 
495 static int timestamp_precision = TSP_SEC;
496 SYSCTL_INT(_vfs, OID_AUTO, timestamp_precision, CTLFLAG_RW,
497     &timestamp_precision, 0, "");
498 
499 /*
500  * Get a current timestamp.
501  */
502 void
503 vfs_timestamp(struct timespec *tsp)
504 {
505 	struct timeval tv;
506 
507 	switch (timestamp_precision) {
508 	case TSP_SEC:
509 		tsp->tv_sec = time_second;
510 		tsp->tv_nsec = 0;
511 		break;
512 	case TSP_HZ:
513 		getnanotime(tsp);
514 		break;
515 	case TSP_USEC:
516 		microtime(&tv);
517 		TIMEVAL_TO_TIMESPEC(&tv, tsp);
518 		break;
519 	case TSP_NSEC:
520 	default:
521 		nanotime(tsp);
522 		break;
523 	}
524 }
525 
526 /*
527  * Set vnode attributes to VNOVAL
528  */
529 void
530 vattr_null(struct vattr *vap)
531 {
532 
533 	vap->va_type = VNON;
534 	vap->va_size = VNOVAL;
535 	vap->va_bytes = VNOVAL;
536 	vap->va_mode = VNOVAL;
537 	vap->va_nlink = VNOVAL;
538 	vap->va_uid = VNOVAL;
539 	vap->va_gid = VNOVAL;
540 	vap->va_fsid = VNOVAL;
541 	vap->va_fileid = VNOVAL;
542 	vap->va_blocksize = VNOVAL;
543 	vap->va_rdev = VNOVAL;
544 	vap->va_atime.tv_sec = VNOVAL;
545 	vap->va_atime.tv_nsec = VNOVAL;
546 	vap->va_mtime.tv_sec = VNOVAL;
547 	vap->va_mtime.tv_nsec = VNOVAL;
548 	vap->va_ctime.tv_sec = VNOVAL;
549 	vap->va_ctime.tv_nsec = VNOVAL;
550 	vap->va_birthtime.tv_sec = VNOVAL;
551 	vap->va_birthtime.tv_nsec = VNOVAL;
552 	vap->va_flags = VNOVAL;
553 	vap->va_gen = VNOVAL;
554 	vap->va_vaflags = 0;
555 }
556 
557 /*
558  * This routine is called when we have too many vnodes.  It attempts
559  * to free <count> vnodes and will potentially free vnodes that still
560  * have VM backing store (VM backing store is typically the cause
561  * of a vnode blowout so we want to do this).  Therefore, this operation
562  * is not considered cheap.
563  *
564  * A number of conditions may prevent a vnode from being reclaimed.
565  * the buffer cache may have references on the vnode, a directory
566  * vnode may still have references due to the namei cache representing
567  * underlying files, or the vnode may be in active use.   It is not
568  * desireable to reuse such vnodes.  These conditions may cause the
569  * number of vnodes to reach some minimum value regardless of what
570  * you set kern.maxvnodes to.  Do not set kern.maxvnodes too low.
571  */
572 static int
573 vlrureclaim(struct mount *mp)
574 {
575 	struct vnode *vp;
576 	int done;
577 	int trigger;
578 	int usevnodes;
579 	int count;
580 
581 	/*
582 	 * Calculate the trigger point, don't allow user
583 	 * screwups to blow us up.   This prevents us from
584 	 * recycling vnodes with lots of resident pages.  We
585 	 * aren't trying to free memory, we are trying to
586 	 * free vnodes.
587 	 */
588 	usevnodes = desiredvnodes;
589 	if (usevnodes <= 0)
590 		usevnodes = 1;
591 	trigger = cnt.v_page_count * 2 / usevnodes;
592 	done = 0;
593 	vn_start_write(NULL, &mp, V_WAIT);
594 	MNT_ILOCK(mp);
595 	count = mp->mnt_nvnodelistsize / 10 + 1;
596 	while (count != 0) {
597 		vp = TAILQ_FIRST(&mp->mnt_nvnodelist);
598 		while (vp != NULL && vp->v_type == VMARKER)
599 			vp = TAILQ_NEXT(vp, v_nmntvnodes);
600 		if (vp == NULL)
601 			break;
602 		TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
603 		TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
604 		--count;
605 		if (!VI_TRYLOCK(vp))
606 			goto next_iter;
607 		/*
608 		 * If it's been deconstructed already, it's still
609 		 * referenced, or it exceeds the trigger, skip it.
610 		 */
611 		if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
612 		    (vp->v_iflag & VI_DOOMED) != 0 || (vp->v_object != NULL &&
613 		    vp->v_object->resident_page_count > trigger)) {
614 			VI_UNLOCK(vp);
615 			goto next_iter;
616 		}
617 		MNT_IUNLOCK(mp);
618 		vholdl(vp);
619 		if (VOP_LOCK(vp, LK_INTERLOCK|LK_EXCLUSIVE|LK_NOWAIT)) {
620 			vdrop(vp);
621 			goto next_iter_mntunlocked;
622 		}
623 		VI_LOCK(vp);
624 		/*
625 		 * v_usecount may have been bumped after VOP_LOCK() dropped
626 		 * the vnode interlock and before it was locked again.
627 		 *
628 		 * It is not necessary to recheck VI_DOOMED because it can
629 		 * only be set by another thread that holds both the vnode
630 		 * lock and vnode interlock.  If another thread has the
631 		 * vnode lock before we get to VOP_LOCK() and obtains the
632 		 * vnode interlock after VOP_LOCK() drops the vnode
633 		 * interlock, the other thread will be unable to drop the
634 		 * vnode lock before our VOP_LOCK() call fails.
635 		 */
636 		if (vp->v_usecount || !LIST_EMPTY(&(vp)->v_cache_src) ||
637 		    (vp->v_object != NULL &&
638 		    vp->v_object->resident_page_count > trigger)) {
639 			VOP_UNLOCK(vp, LK_INTERLOCK);
640 			goto next_iter_mntunlocked;
641 		}
642 		KASSERT((vp->v_iflag & VI_DOOMED) == 0,
643 		    ("VI_DOOMED unexpectedly detected in vlrureclaim()"));
644 		vgonel(vp);
645 		VOP_UNLOCK(vp, 0);
646 		vdropl(vp);
647 		done++;
648 next_iter_mntunlocked:
649 		if ((count % 256) != 0)
650 			goto relock_mnt;
651 		goto yield;
652 next_iter:
653 		if ((count % 256) != 0)
654 			continue;
655 		MNT_IUNLOCK(mp);
656 yield:
657 		uio_yield();
658 relock_mnt:
659 		MNT_ILOCK(mp);
660 	}
661 	MNT_IUNLOCK(mp);
662 	vn_finished_write(mp);
663 	return done;
664 }
665 
666 /*
667  * Attempt to keep the free list at wantfreevnodes length.
668  */
669 static void
670 vnlru_free(int count)
671 {
672 	struct vnode *vp;
673 	int vfslocked;
674 
675 	mtx_assert(&vnode_free_list_mtx, MA_OWNED);
676 	for (; count > 0; count--) {
677 		vp = TAILQ_FIRST(&vnode_free_list);
678 		/*
679 		 * The list can be modified while the free_list_mtx
680 		 * has been dropped and vp could be NULL here.
681 		 */
682 		if (!vp)
683 			break;
684 		VNASSERT(vp->v_op != NULL, vp,
685 		    ("vnlru_free: vnode already reclaimed."));
686 		TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
687 		/*
688 		 * Don't recycle if we can't get the interlock.
689 		 */
690 		if (!VI_TRYLOCK(vp)) {
691 			TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
692 			continue;
693 		}
694 		VNASSERT(VCANRECYCLE(vp), vp,
695 		    ("vp inconsistent on freelist"));
696 		freevnodes--;
697 		vp->v_iflag &= ~VI_FREE;
698 		vholdl(vp);
699 		mtx_unlock(&vnode_free_list_mtx);
700 		VI_UNLOCK(vp);
701 		vfslocked = VFS_LOCK_GIANT(vp->v_mount);
702 		vtryrecycle(vp);
703 		VFS_UNLOCK_GIANT(vfslocked);
704 		/*
705 		 * If the recycled succeeded this vdrop will actually free
706 		 * the vnode.  If not it will simply place it back on
707 		 * the free list.
708 		 */
709 		vdrop(vp);
710 		mtx_lock(&vnode_free_list_mtx);
711 	}
712 }
713 /*
714  * Attempt to recycle vnodes in a context that is always safe to block.
715  * Calling vlrurecycle() from the bowels of filesystem code has some
716  * interesting deadlock problems.
717  */
718 static struct proc *vnlruproc;
719 static int vnlruproc_sig;
720 
721 static void
722 vnlru_proc(void)
723 {
724 	struct mount *mp, *nmp;
725 	int done;
726 	struct proc *p = vnlruproc;
727 
728 	EVENTHANDLER_REGISTER(shutdown_pre_sync, kproc_shutdown, p,
729 	    SHUTDOWN_PRI_FIRST);
730 
731 	mtx_lock(&Giant);
732 
733 	for (;;) {
734 		kproc_suspend_check(p);
735 		mtx_lock(&vnode_free_list_mtx);
736 		if (freevnodes > wantfreevnodes)
737 			vnlru_free(freevnodes - wantfreevnodes);
738 		if (numvnodes <= desiredvnodes * 9 / 10) {
739 			vnlruproc_sig = 0;
740 			wakeup(&vnlruproc_sig);
741 			msleep(vnlruproc, &vnode_free_list_mtx,
742 			    PVFS|PDROP, "vlruwt", hz);
743 			continue;
744 		}
745 		mtx_unlock(&vnode_free_list_mtx);
746 		done = 0;
747 		mtx_lock(&mountlist_mtx);
748 		for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
749 			int vfsunlocked;
750 			if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx)) {
751 				nmp = TAILQ_NEXT(mp, mnt_list);
752 				continue;
753 			}
754 			if (!VFS_NEEDSGIANT(mp)) {
755 				mtx_unlock(&Giant);
756 				vfsunlocked = 1;
757 			} else
758 				vfsunlocked = 0;
759 			done += vlrureclaim(mp);
760 			if (vfsunlocked)
761 				mtx_lock(&Giant);
762 			mtx_lock(&mountlist_mtx);
763 			nmp = TAILQ_NEXT(mp, mnt_list);
764 			vfs_unbusy(mp);
765 		}
766 		mtx_unlock(&mountlist_mtx);
767 		if (done == 0) {
768 			EVENTHANDLER_INVOKE(vfs_lowvnodes, desiredvnodes / 10);
769 #if 0
770 			/* These messages are temporary debugging aids */
771 			if (vnlru_nowhere < 5)
772 				printf("vnlru process getting nowhere..\n");
773 			else if (vnlru_nowhere == 5)
774 				printf("vnlru process messages stopped.\n");
775 #endif
776 			vnlru_nowhere++;
777 			tsleep(vnlruproc, PPAUSE, "vlrup", hz * 3);
778 		} else
779 			uio_yield();
780 	}
781 }
782 
783 static struct kproc_desc vnlru_kp = {
784 	"vnlru",
785 	vnlru_proc,
786 	&vnlruproc
787 };
788 SYSINIT(vnlru, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start,
789     &vnlru_kp);
790 
791 /*
792  * Routines having to do with the management of the vnode table.
793  */
794 
795 static void
796 vdestroy(struct vnode *vp)
797 {
798 	struct bufobj *bo;
799 
800 	CTR1(KTR_VFS, "vdestroy vp %p", vp);
801 	mtx_lock(&vnode_free_list_mtx);
802 	numvnodes--;
803 	mtx_unlock(&vnode_free_list_mtx);
804 	bo = &vp->v_bufobj;
805 	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp,
806 	    ("cleaned vnode still on the free list."));
807 	VNASSERT(vp->v_data == NULL, vp, ("cleaned vnode isn't"));
808 	VNASSERT(vp->v_holdcnt == 0, vp, ("Non-zero hold count"));
809 	VNASSERT(vp->v_usecount == 0, vp, ("Non-zero use count"));
810 	VNASSERT(vp->v_writecount == 0, vp, ("Non-zero write count"));
811 	VNASSERT(bo->bo_numoutput == 0, vp, ("Clean vnode has pending I/O's"));
812 	VNASSERT(bo->bo_clean.bv_cnt == 0, vp, ("cleanbufcnt not 0"));
813 	VNASSERT(bo->bo_clean.bv_root == NULL, vp, ("cleanblkroot not NULL"));
814 	VNASSERT(bo->bo_dirty.bv_cnt == 0, vp, ("dirtybufcnt not 0"));
815 	VNASSERT(bo->bo_dirty.bv_root == NULL, vp, ("dirtyblkroot not NULL"));
816 	VNASSERT(TAILQ_EMPTY(&vp->v_cache_dst), vp, ("vp has namecache dst"));
817 	VNASSERT(LIST_EMPTY(&vp->v_cache_src), vp, ("vp has namecache src"));
818 	VI_UNLOCK(vp);
819 #ifdef MAC
820 	mac_vnode_destroy(vp);
821 #endif
822 	if (vp->v_pollinfo != NULL) {
823 		knlist_destroy(&vp->v_pollinfo->vpi_selinfo.si_note);
824 		mtx_destroy(&vp->v_pollinfo->vpi_lock);
825 		uma_zfree(vnodepoll_zone, vp->v_pollinfo);
826 	}
827 #ifdef INVARIANTS
828 	/* XXX Elsewhere we can detect an already freed vnode via NULL v_op. */
829 	vp->v_op = NULL;
830 #endif
831 	lockdestroy(vp->v_vnlock);
832 	mtx_destroy(&vp->v_interlock);
833 	mtx_destroy(BO_MTX(bo));
834 	uma_zfree(vnode_zone, vp);
835 }
836 
837 /*
838  * Try to recycle a freed vnode.  We abort if anyone picks up a reference
839  * before we actually vgone().  This function must be called with the vnode
840  * held to prevent the vnode from being returned to the free list midway
841  * through vgone().
842  */
843 static int
844 vtryrecycle(struct vnode *vp)
845 {
846 	struct mount *vnmp;
847 
848 	CTR1(KTR_VFS, "vtryrecycle: trying vp %p", vp);
849 	VNASSERT(vp->v_holdcnt, vp,
850 	    ("vtryrecycle: Recycling vp %p without a reference.", vp));
851 	/*
852 	 * This vnode may found and locked via some other list, if so we
853 	 * can't recycle it yet.
854 	 */
855 	if (VOP_LOCK(vp, LK_EXCLUSIVE | LK_NOWAIT) != 0)
856 		return (EWOULDBLOCK);
857 	/*
858 	 * Don't recycle if its filesystem is being suspended.
859 	 */
860 	if (vn_start_write(vp, &vnmp, V_NOWAIT) != 0) {
861 		VOP_UNLOCK(vp, 0);
862 		return (EBUSY);
863 	}
864 	/*
865 	 * If we got this far, we need to acquire the interlock and see if
866 	 * anyone picked up this vnode from another list.  If not, we will
867 	 * mark it with DOOMED via vgonel() so that anyone who does find it
868 	 * will skip over it.
869 	 */
870 	VI_LOCK(vp);
871 	if (vp->v_usecount) {
872 		VOP_UNLOCK(vp, LK_INTERLOCK);
873 		vn_finished_write(vnmp);
874 		return (EBUSY);
875 	}
876 	if ((vp->v_iflag & VI_DOOMED) == 0)
877 		vgonel(vp);
878 	VOP_UNLOCK(vp, LK_INTERLOCK);
879 	vn_finished_write(vnmp);
880 	CTR1(KTR_VFS, "vtryrecycle: recycled vp %p", vp);
881 	return (0);
882 }
883 
884 /*
885  * Return the next vnode from the free list.
886  */
887 int
888 getnewvnode(const char *tag, struct mount *mp, struct vop_vector *vops,
889     struct vnode **vpp)
890 {
891 	struct vnode *vp = NULL;
892 	struct bufobj *bo;
893 
894 	mtx_lock(&vnode_free_list_mtx);
895 	/*
896 	 * Lend our context to reclaim vnodes if they've exceeded the max.
897 	 */
898 	if (freevnodes > wantfreevnodes)
899 		vnlru_free(1);
900 	/*
901 	 * Wait for available vnodes.
902 	 */
903 	if (numvnodes > desiredvnodes) {
904 		if (mp != NULL && (mp->mnt_kern_flag & MNTK_SUSPEND)) {
905 			/*
906 			 * File system is beeing suspended, we cannot risk a
907 			 * deadlock here, so allocate new vnode anyway.
908 			 */
909 			if (freevnodes > wantfreevnodes)
910 				vnlru_free(freevnodes - wantfreevnodes);
911 			goto alloc;
912 		}
913 		if (vnlruproc_sig == 0) {
914 			vnlruproc_sig = 1;	/* avoid unnecessary wakeups */
915 			wakeup(vnlruproc);
916 		}
917 		msleep(&vnlruproc_sig, &vnode_free_list_mtx, PVFS,
918 		    "vlruwk", hz);
919 #if 0	/* XXX Not all VFS_VGET/ffs_vget callers check returns. */
920 		if (numvnodes > desiredvnodes) {
921 			mtx_unlock(&vnode_free_list_mtx);
922 			return (ENFILE);
923 		}
924 #endif
925 	}
926 alloc:
927 	numvnodes++;
928 	mtx_unlock(&vnode_free_list_mtx);
929 	vp = (struct vnode *) uma_zalloc(vnode_zone, M_WAITOK|M_ZERO);
930 	/*
931 	 * Setup locks.
932 	 */
933 	vp->v_vnlock = &vp->v_lock;
934 	mtx_init(&vp->v_interlock, "vnode interlock", NULL, MTX_DEF);
935 	/*
936 	 * By default, don't allow shared locks unless filesystems
937 	 * opt-in.
938 	 */
939 	lockinit(vp->v_vnlock, PVFS, tag, VLKTIMEOUT, LK_NOSHARE);
940 	/*
941 	 * Initialize bufobj.
942 	 */
943 	bo = &vp->v_bufobj;
944 	bo->__bo_vnode = vp;
945 	mtx_init(BO_MTX(bo), "bufobj interlock", NULL, MTX_DEF);
946 	bo->bo_ops = &buf_ops_bio;
947 	bo->bo_private = vp;
948 	TAILQ_INIT(&bo->bo_clean.bv_hd);
949 	TAILQ_INIT(&bo->bo_dirty.bv_hd);
950 	/*
951 	 * Initialize namecache.
952 	 */
953 	LIST_INIT(&vp->v_cache_src);
954 	TAILQ_INIT(&vp->v_cache_dst);
955 	/*
956 	 * Finalize various vnode identity bits.
957 	 */
958 	vp->v_type = VNON;
959 	vp->v_tag = tag;
960 	vp->v_op = vops;
961 	v_incr_usecount(vp);
962 	vp->v_data = 0;
963 #ifdef MAC
964 	mac_vnode_init(vp);
965 	if (mp != NULL && (mp->mnt_flag & MNT_MULTILABEL) == 0)
966 		mac_vnode_associate_singlelabel(mp, vp);
967 	else if (mp == NULL && vops != &dead_vnodeops)
968 		printf("NULL mp in getnewvnode()\n");
969 #endif
970 	if (mp != NULL) {
971 		bo->bo_bsize = mp->mnt_stat.f_iosize;
972 		if ((mp->mnt_kern_flag & MNTK_NOKNOTE) != 0)
973 			vp->v_vflag |= VV_NOKNOTE;
974 	}
975 
976 	CTR2(KTR_VFS, "getnewvnode: mp %p vp %p", mp, vp);
977 	*vpp = vp;
978 	return (0);
979 }
980 
981 /*
982  * Delete from old mount point vnode list, if on one.
983  */
984 static void
985 delmntque(struct vnode *vp)
986 {
987 	struct mount *mp;
988 
989 	mp = vp->v_mount;
990 	if (mp == NULL)
991 		return;
992 	MNT_ILOCK(mp);
993 	vp->v_mount = NULL;
994 	VNASSERT(mp->mnt_nvnodelistsize > 0, vp,
995 		("bad mount point vnode list size"));
996 	TAILQ_REMOVE(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
997 	mp->mnt_nvnodelistsize--;
998 	MNT_REL(mp);
999 	MNT_IUNLOCK(mp);
1000 }
1001 
1002 static void
1003 insmntque_stddtr(struct vnode *vp, void *dtr_arg)
1004 {
1005 
1006 	vp->v_data = NULL;
1007 	vp->v_op = &dead_vnodeops;
1008 	/* XXX non mp-safe fs may still call insmntque with vnode
1009 	   unlocked */
1010 	if (!VOP_ISLOCKED(vp))
1011 		vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1012 	vgone(vp);
1013 	vput(vp);
1014 }
1015 
1016 /*
1017  * Insert into list of vnodes for the new mount point, if available.
1018  */
1019 int
1020 insmntque1(struct vnode *vp, struct mount *mp,
1021 	void (*dtr)(struct vnode *, void *), void *dtr_arg)
1022 {
1023 	int locked;
1024 
1025 	KASSERT(vp->v_mount == NULL,
1026 		("insmntque: vnode already on per mount vnode list"));
1027 	VNASSERT(mp != NULL, vp, ("Don't call insmntque(foo, NULL)"));
1028 #ifdef DEBUG_VFS_LOCKS
1029 	if (!VFS_NEEDSGIANT(mp))
1030 		ASSERT_VOP_ELOCKED(vp,
1031 		    "insmntque: mp-safe fs and non-locked vp");
1032 #endif
1033 	MNT_ILOCK(mp);
1034 	if ((mp->mnt_kern_flag & MNTK_NOINSMNTQ) != 0 &&
1035 	    ((mp->mnt_kern_flag & MNTK_UNMOUNTF) != 0 ||
1036 	     mp->mnt_nvnodelistsize == 0)) {
1037 		locked = VOP_ISLOCKED(vp);
1038 		if (!locked || (locked == LK_EXCLUSIVE &&
1039 		     (vp->v_vflag & VV_FORCEINSMQ) == 0)) {
1040 			MNT_IUNLOCK(mp);
1041 			if (dtr != NULL)
1042 				dtr(vp, dtr_arg);
1043 			return (EBUSY);
1044 		}
1045 	}
1046 	vp->v_mount = mp;
1047 	MNT_REF(mp);
1048 	TAILQ_INSERT_TAIL(&mp->mnt_nvnodelist, vp, v_nmntvnodes);
1049 	VNASSERT(mp->mnt_nvnodelistsize >= 0, vp,
1050 		("neg mount point vnode list size"));
1051 	mp->mnt_nvnodelistsize++;
1052 	MNT_IUNLOCK(mp);
1053 	return (0);
1054 }
1055 
1056 int
1057 insmntque(struct vnode *vp, struct mount *mp)
1058 {
1059 
1060 	return (insmntque1(vp, mp, insmntque_stddtr, NULL));
1061 }
1062 
1063 /*
1064  * Flush out and invalidate all buffers associated with a bufobj
1065  * Called with the underlying object locked.
1066  */
1067 int
1068 bufobj_invalbuf(struct bufobj *bo, int flags, int slpflag, int slptimeo)
1069 {
1070 	int error;
1071 
1072 	BO_LOCK(bo);
1073 	if (flags & V_SAVE) {
1074 		error = bufobj_wwait(bo, slpflag, slptimeo);
1075 		if (error) {
1076 			BO_UNLOCK(bo);
1077 			return (error);
1078 		}
1079 		if (bo->bo_dirty.bv_cnt > 0) {
1080 			BO_UNLOCK(bo);
1081 			if ((error = BO_SYNC(bo, MNT_WAIT)) != 0)
1082 				return (error);
1083 			/*
1084 			 * XXX We could save a lock/unlock if this was only
1085 			 * enabled under INVARIANTS
1086 			 */
1087 			BO_LOCK(bo);
1088 			if (bo->bo_numoutput > 0 || bo->bo_dirty.bv_cnt > 0)
1089 				panic("vinvalbuf: dirty bufs");
1090 		}
1091 	}
1092 	/*
1093 	 * If you alter this loop please notice that interlock is dropped and
1094 	 * reacquired in flushbuflist.  Special care is needed to ensure that
1095 	 * no race conditions occur from this.
1096 	 */
1097 	do {
1098 		error = flushbuflist(&bo->bo_clean,
1099 		    flags, bo, slpflag, slptimeo);
1100 		if (error == 0)
1101 			error = flushbuflist(&bo->bo_dirty,
1102 			    flags, bo, slpflag, slptimeo);
1103 		if (error != 0 && error != EAGAIN) {
1104 			BO_UNLOCK(bo);
1105 			return (error);
1106 		}
1107 	} while (error != 0);
1108 
1109 	/*
1110 	 * Wait for I/O to complete.  XXX needs cleaning up.  The vnode can
1111 	 * have write I/O in-progress but if there is a VM object then the
1112 	 * VM object can also have read-I/O in-progress.
1113 	 */
1114 	do {
1115 		bufobj_wwait(bo, 0, 0);
1116 		BO_UNLOCK(bo);
1117 		if (bo->bo_object != NULL) {
1118 			VM_OBJECT_LOCK(bo->bo_object);
1119 			vm_object_pip_wait(bo->bo_object, "bovlbx");
1120 			VM_OBJECT_UNLOCK(bo->bo_object);
1121 		}
1122 		BO_LOCK(bo);
1123 	} while (bo->bo_numoutput > 0);
1124 	BO_UNLOCK(bo);
1125 
1126 	/*
1127 	 * Destroy the copy in the VM cache, too.
1128 	 */
1129 	if (bo->bo_object != NULL) {
1130 		VM_OBJECT_LOCK(bo->bo_object);
1131 		vm_object_page_remove(bo->bo_object, 0, 0,
1132 			(flags & V_SAVE) ? TRUE : FALSE);
1133 		VM_OBJECT_UNLOCK(bo->bo_object);
1134 	}
1135 
1136 #ifdef INVARIANTS
1137 	BO_LOCK(bo);
1138 	if ((flags & (V_ALT | V_NORMAL)) == 0 &&
1139 	    (bo->bo_dirty.bv_cnt > 0 || bo->bo_clean.bv_cnt > 0))
1140 		panic("vinvalbuf: flush failed");
1141 	BO_UNLOCK(bo);
1142 #endif
1143 	return (0);
1144 }
1145 
1146 /*
1147  * Flush out and invalidate all buffers associated with a vnode.
1148  * Called with the underlying object locked.
1149  */
1150 int
1151 vinvalbuf(struct vnode *vp, int flags, int slpflag, int slptimeo)
1152 {
1153 
1154 	CTR2(KTR_VFS, "vinvalbuf vp %p flags %d", vp, flags);
1155 	ASSERT_VOP_LOCKED(vp, "vinvalbuf");
1156 	return (bufobj_invalbuf(&vp->v_bufobj, flags, slpflag, slptimeo));
1157 }
1158 
1159 /*
1160  * Flush out buffers on the specified list.
1161  *
1162  */
1163 static int
1164 flushbuflist( struct bufv *bufv, int flags, struct bufobj *bo, int slpflag,
1165     int slptimeo)
1166 {
1167 	struct buf *bp, *nbp;
1168 	int retval, error;
1169 	daddr_t lblkno;
1170 	b_xflags_t xflags;
1171 
1172 	ASSERT_BO_LOCKED(bo);
1173 
1174 	retval = 0;
1175 	TAILQ_FOREACH_SAFE(bp, &bufv->bv_hd, b_bobufs, nbp) {
1176 		if (((flags & V_NORMAL) && (bp->b_xflags & BX_ALTDATA)) ||
1177 		    ((flags & V_ALT) && (bp->b_xflags & BX_ALTDATA) == 0)) {
1178 			continue;
1179 		}
1180 		lblkno = 0;
1181 		xflags = 0;
1182 		if (nbp != NULL) {
1183 			lblkno = nbp->b_lblkno;
1184 			xflags = nbp->b_xflags &
1185 				(BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN);
1186 		}
1187 		retval = EAGAIN;
1188 		error = BUF_TIMELOCK(bp,
1189 		    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK, BO_MTX(bo),
1190 		    "flushbuf", slpflag, slptimeo);
1191 		if (error) {
1192 			BO_LOCK(bo);
1193 			return (error != ENOLCK ? error : EAGAIN);
1194 		}
1195 		KASSERT(bp->b_bufobj == bo,
1196 		    ("bp %p wrong b_bufobj %p should be %p",
1197 		    bp, bp->b_bufobj, bo));
1198 		if (bp->b_bufobj != bo) {	/* XXX: necessary ? */
1199 			BUF_UNLOCK(bp);
1200 			BO_LOCK(bo);
1201 			return (EAGAIN);
1202 		}
1203 		/*
1204 		 * XXX Since there are no node locks for NFS, I
1205 		 * believe there is a slight chance that a delayed
1206 		 * write will occur while sleeping just above, so
1207 		 * check for it.
1208 		 */
1209 		if (((bp->b_flags & (B_DELWRI | B_INVAL)) == B_DELWRI) &&
1210 		    (flags & V_SAVE)) {
1211 			bremfree(bp);
1212 			bp->b_flags |= B_ASYNC;
1213 			bwrite(bp);
1214 			BO_LOCK(bo);
1215 			return (EAGAIN);	/* XXX: why not loop ? */
1216 		}
1217 		bremfree(bp);
1218 		bp->b_flags |= (B_INVAL | B_RELBUF);
1219 		bp->b_flags &= ~B_ASYNC;
1220 		brelse(bp);
1221 		BO_LOCK(bo);
1222 		if (nbp != NULL &&
1223 		    (nbp->b_bufobj != bo ||
1224 		     nbp->b_lblkno != lblkno ||
1225 		     (nbp->b_xflags &
1226 		      (BX_BKGRDMARKER | BX_VNDIRTY | BX_VNCLEAN)) != xflags))
1227 			break;			/* nbp invalid */
1228 	}
1229 	return (retval);
1230 }
1231 
1232 /*
1233  * Truncate a file's buffer and pages to a specified length.  This
1234  * is in lieu of the old vinvalbuf mechanism, which performed unneeded
1235  * sync activity.
1236  */
1237 int
1238 vtruncbuf(struct vnode *vp, struct ucred *cred, struct thread *td,
1239     off_t length, int blksize)
1240 {
1241 	struct buf *bp, *nbp;
1242 	int anyfreed;
1243 	int trunclbn;
1244 	struct bufobj *bo;
1245 
1246 	CTR2(KTR_VFS, "vtruncbuf vp %p length %jd", vp, length);
1247 	/*
1248 	 * Round up to the *next* lbn.
1249 	 */
1250 	trunclbn = (length + blksize - 1) / blksize;
1251 
1252 	ASSERT_VOP_LOCKED(vp, "vtruncbuf");
1253 restart:
1254 	bo = &vp->v_bufobj;
1255 	BO_LOCK(bo);
1256 	anyfreed = 1;
1257 	for (;anyfreed;) {
1258 		anyfreed = 0;
1259 		TAILQ_FOREACH_SAFE(bp, &bo->bo_clean.bv_hd, b_bobufs, nbp) {
1260 			if (bp->b_lblkno < trunclbn)
1261 				continue;
1262 			if (BUF_LOCK(bp,
1263 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1264 			    BO_MTX(bo)) == ENOLCK)
1265 				goto restart;
1266 
1267 			bremfree(bp);
1268 			bp->b_flags |= (B_INVAL | B_RELBUF);
1269 			bp->b_flags &= ~B_ASYNC;
1270 			brelse(bp);
1271 			anyfreed = 1;
1272 
1273 			if (nbp != NULL &&
1274 			    (((nbp->b_xflags & BX_VNCLEAN) == 0) ||
1275 			    (nbp->b_vp != vp) ||
1276 			    (nbp->b_flags & B_DELWRI))) {
1277 				goto restart;
1278 			}
1279 			BO_LOCK(bo);
1280 		}
1281 
1282 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1283 			if (bp->b_lblkno < trunclbn)
1284 				continue;
1285 			if (BUF_LOCK(bp,
1286 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1287 			    BO_MTX(bo)) == ENOLCK)
1288 				goto restart;
1289 			bremfree(bp);
1290 			bp->b_flags |= (B_INVAL | B_RELBUF);
1291 			bp->b_flags &= ~B_ASYNC;
1292 			brelse(bp);
1293 			anyfreed = 1;
1294 			if (nbp != NULL &&
1295 			    (((nbp->b_xflags & BX_VNDIRTY) == 0) ||
1296 			    (nbp->b_vp != vp) ||
1297 			    (nbp->b_flags & B_DELWRI) == 0)) {
1298 				goto restart;
1299 			}
1300 			BO_LOCK(bo);
1301 		}
1302 	}
1303 
1304 	if (length > 0) {
1305 restartsync:
1306 		TAILQ_FOREACH_SAFE(bp, &bo->bo_dirty.bv_hd, b_bobufs, nbp) {
1307 			if (bp->b_lblkno > 0)
1308 				continue;
1309 			/*
1310 			 * Since we hold the vnode lock this should only
1311 			 * fail if we're racing with the buf daemon.
1312 			 */
1313 			if (BUF_LOCK(bp,
1314 			    LK_EXCLUSIVE | LK_SLEEPFAIL | LK_INTERLOCK,
1315 			    BO_MTX(bo)) == ENOLCK) {
1316 				goto restart;
1317 			}
1318 			VNASSERT((bp->b_flags & B_DELWRI), vp,
1319 			    ("buf(%p) on dirty queue without DELWRI", bp));
1320 
1321 			bremfree(bp);
1322 			bawrite(bp);
1323 			BO_LOCK(bo);
1324 			goto restartsync;
1325 		}
1326 	}
1327 
1328 	bufobj_wwait(bo, 0, 0);
1329 	BO_UNLOCK(bo);
1330 	vnode_pager_setsize(vp, length);
1331 
1332 	return (0);
1333 }
1334 
1335 /*
1336  * buf_splay() - splay tree core for the clean/dirty list of buffers in
1337  * 		 a vnode.
1338  *
1339  *	NOTE: We have to deal with the special case of a background bitmap
1340  *	buffer, a situation where two buffers will have the same logical
1341  *	block offset.  We want (1) only the foreground buffer to be accessed
1342  *	in a lookup and (2) must differentiate between the foreground and
1343  *	background buffer in the splay tree algorithm because the splay
1344  *	tree cannot normally handle multiple entities with the same 'index'.
1345  *	We accomplish this by adding differentiating flags to the splay tree's
1346  *	numerical domain.
1347  */
1348 static
1349 struct buf *
1350 buf_splay(daddr_t lblkno, b_xflags_t xflags, struct buf *root)
1351 {
1352 	struct buf dummy;
1353 	struct buf *lefttreemax, *righttreemin, *y;
1354 
1355 	if (root == NULL)
1356 		return (NULL);
1357 	lefttreemax = righttreemin = &dummy;
1358 	for (;;) {
1359 		if (lblkno < root->b_lblkno ||
1360 		    (lblkno == root->b_lblkno &&
1361 		    (xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1362 			if ((y = root->b_left) == NULL)
1363 				break;
1364 			if (lblkno < y->b_lblkno) {
1365 				/* Rotate right. */
1366 				root->b_left = y->b_right;
1367 				y->b_right = root;
1368 				root = y;
1369 				if ((y = root->b_left) == NULL)
1370 					break;
1371 			}
1372 			/* Link into the new root's right tree. */
1373 			righttreemin->b_left = root;
1374 			righttreemin = root;
1375 		} else if (lblkno > root->b_lblkno ||
1376 		    (lblkno == root->b_lblkno &&
1377 		    (xflags & BX_BKGRDMARKER) > (root->b_xflags & BX_BKGRDMARKER))) {
1378 			if ((y = root->b_right) == NULL)
1379 				break;
1380 			if (lblkno > y->b_lblkno) {
1381 				/* Rotate left. */
1382 				root->b_right = y->b_left;
1383 				y->b_left = root;
1384 				root = y;
1385 				if ((y = root->b_right) == NULL)
1386 					break;
1387 			}
1388 			/* Link into the new root's left tree. */
1389 			lefttreemax->b_right = root;
1390 			lefttreemax = root;
1391 		} else {
1392 			break;
1393 		}
1394 		root = y;
1395 	}
1396 	/* Assemble the new root. */
1397 	lefttreemax->b_right = root->b_left;
1398 	righttreemin->b_left = root->b_right;
1399 	root->b_left = dummy.b_right;
1400 	root->b_right = dummy.b_left;
1401 	return (root);
1402 }
1403 
1404 static void
1405 buf_vlist_remove(struct buf *bp)
1406 {
1407 	struct buf *root;
1408 	struct bufv *bv;
1409 
1410 	KASSERT(bp->b_bufobj != NULL, ("No b_bufobj %p", bp));
1411 	ASSERT_BO_LOCKED(bp->b_bufobj);
1412 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) !=
1413 	    (BX_VNDIRTY|BX_VNCLEAN),
1414 	    ("buf_vlist_remove: Buf %p is on two lists", bp));
1415 	if (bp->b_xflags & BX_VNDIRTY)
1416 		bv = &bp->b_bufobj->bo_dirty;
1417 	else
1418 		bv = &bp->b_bufobj->bo_clean;
1419 	if (bp != bv->bv_root) {
1420 		root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1421 		KASSERT(root == bp, ("splay lookup failed in remove"));
1422 	}
1423 	if (bp->b_left == NULL) {
1424 		root = bp->b_right;
1425 	} else {
1426 		root = buf_splay(bp->b_lblkno, bp->b_xflags, bp->b_left);
1427 		root->b_right = bp->b_right;
1428 	}
1429 	bv->bv_root = root;
1430 	TAILQ_REMOVE(&bv->bv_hd, bp, b_bobufs);
1431 	bv->bv_cnt--;
1432 	bp->b_xflags &= ~(BX_VNDIRTY | BX_VNCLEAN);
1433 }
1434 
1435 /*
1436  * Add the buffer to the sorted clean or dirty block list using a
1437  * splay tree algorithm.
1438  *
1439  * NOTE: xflags is passed as a constant, optimizing this inline function!
1440  */
1441 static void
1442 buf_vlist_add(struct buf *bp, struct bufobj *bo, b_xflags_t xflags)
1443 {
1444 	struct buf *root;
1445 	struct bufv *bv;
1446 
1447 	ASSERT_BO_LOCKED(bo);
1448 	KASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0,
1449 	    ("buf_vlist_add: Buf %p has existing xflags %d", bp, bp->b_xflags));
1450 	bp->b_xflags |= xflags;
1451 	if (xflags & BX_VNDIRTY)
1452 		bv = &bo->bo_dirty;
1453 	else
1454 		bv = &bo->bo_clean;
1455 
1456 	root = buf_splay(bp->b_lblkno, bp->b_xflags, bv->bv_root);
1457 	if (root == NULL) {
1458 		bp->b_left = NULL;
1459 		bp->b_right = NULL;
1460 		TAILQ_INSERT_TAIL(&bv->bv_hd, bp, b_bobufs);
1461 	} else if (bp->b_lblkno < root->b_lblkno ||
1462 	    (bp->b_lblkno == root->b_lblkno &&
1463 	    (bp->b_xflags & BX_BKGRDMARKER) < (root->b_xflags & BX_BKGRDMARKER))) {
1464 		bp->b_left = root->b_left;
1465 		bp->b_right = root;
1466 		root->b_left = NULL;
1467 		TAILQ_INSERT_BEFORE(root, bp, b_bobufs);
1468 	} else {
1469 		bp->b_right = root->b_right;
1470 		bp->b_left = root;
1471 		root->b_right = NULL;
1472 		TAILQ_INSERT_AFTER(&bv->bv_hd, root, bp, b_bobufs);
1473 	}
1474 	bv->bv_cnt++;
1475 	bv->bv_root = bp;
1476 }
1477 
1478 /*
1479  * Lookup a buffer using the splay tree.  Note that we specifically avoid
1480  * shadow buffers used in background bitmap writes.
1481  *
1482  * This code isn't quite efficient as it could be because we are maintaining
1483  * two sorted lists and do not know which list the block resides in.
1484  *
1485  * During a "make buildworld" the desired buffer is found at one of
1486  * the roots more than 60% of the time.  Thus, checking both roots
1487  * before performing either splay eliminates unnecessary splays on the
1488  * first tree splayed.
1489  */
1490 struct buf *
1491 gbincore(struct bufobj *bo, daddr_t lblkno)
1492 {
1493 	struct buf *bp;
1494 
1495 	ASSERT_BO_LOCKED(bo);
1496 	if ((bp = bo->bo_clean.bv_root) != NULL &&
1497 	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1498 		return (bp);
1499 	if ((bp = bo->bo_dirty.bv_root) != NULL &&
1500 	    bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1501 		return (bp);
1502 	if ((bp = bo->bo_clean.bv_root) != NULL) {
1503 		bo->bo_clean.bv_root = bp = buf_splay(lblkno, 0, bp);
1504 		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1505 			return (bp);
1506 	}
1507 	if ((bp = bo->bo_dirty.bv_root) != NULL) {
1508 		bo->bo_dirty.bv_root = bp = buf_splay(lblkno, 0, bp);
1509 		if (bp->b_lblkno == lblkno && !(bp->b_xflags & BX_BKGRDMARKER))
1510 			return (bp);
1511 	}
1512 	return (NULL);
1513 }
1514 
1515 /*
1516  * Associate a buffer with a vnode.
1517  */
1518 void
1519 bgetvp(struct vnode *vp, struct buf *bp)
1520 {
1521 	struct bufobj *bo;
1522 
1523 	bo = &vp->v_bufobj;
1524 	ASSERT_BO_LOCKED(bo);
1525 	VNASSERT(bp->b_vp == NULL, bp->b_vp, ("bgetvp: not free"));
1526 
1527 	CTR3(KTR_BUF, "bgetvp(%p) vp %p flags %X", bp, vp, bp->b_flags);
1528 	VNASSERT((bp->b_xflags & (BX_VNDIRTY|BX_VNCLEAN)) == 0, vp,
1529 	    ("bgetvp: bp already attached! %p", bp));
1530 
1531 	vhold(vp);
1532 	if (VFS_NEEDSGIANT(vp->v_mount) || bo->bo_flag & BO_NEEDSGIANT)
1533 		bp->b_flags |= B_NEEDSGIANT;
1534 	bp->b_vp = vp;
1535 	bp->b_bufobj = bo;
1536 	/*
1537 	 * Insert onto list for new vnode.
1538 	 */
1539 	buf_vlist_add(bp, bo, BX_VNCLEAN);
1540 }
1541 
1542 /*
1543  * Disassociate a buffer from a vnode.
1544  */
1545 void
1546 brelvp(struct buf *bp)
1547 {
1548 	struct bufobj *bo;
1549 	struct vnode *vp;
1550 
1551 	CTR3(KTR_BUF, "brelvp(%p) vp %p flags %X", bp, bp->b_vp, bp->b_flags);
1552 	KASSERT(bp->b_vp != NULL, ("brelvp: NULL"));
1553 
1554 	/*
1555 	 * Delete from old vnode list, if on one.
1556 	 */
1557 	vp = bp->b_vp;		/* XXX */
1558 	bo = bp->b_bufobj;
1559 	BO_LOCK(bo);
1560 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1561 		buf_vlist_remove(bp);
1562 	else
1563 		panic("brelvp: Buffer %p not on queue.", bp);
1564 	if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1565 		bo->bo_flag &= ~BO_ONWORKLST;
1566 		mtx_lock(&sync_mtx);
1567 		LIST_REMOVE(bo, bo_synclist);
1568 		syncer_worklist_len--;
1569 		mtx_unlock(&sync_mtx);
1570 	}
1571 	bp->b_flags &= ~B_NEEDSGIANT;
1572 	bp->b_vp = NULL;
1573 	bp->b_bufobj = NULL;
1574 	BO_UNLOCK(bo);
1575 	vdrop(vp);
1576 }
1577 
1578 /*
1579  * Add an item to the syncer work queue.
1580  */
1581 static void
1582 vn_syncer_add_to_worklist(struct bufobj *bo, int delay)
1583 {
1584 	int queue, slot;
1585 
1586 	ASSERT_BO_LOCKED(bo);
1587 
1588 	mtx_lock(&sync_mtx);
1589 	if (bo->bo_flag & BO_ONWORKLST)
1590 		LIST_REMOVE(bo, bo_synclist);
1591 	else {
1592 		bo->bo_flag |= BO_ONWORKLST;
1593 		syncer_worklist_len++;
1594 	}
1595 
1596 	if (delay > syncer_maxdelay - 2)
1597 		delay = syncer_maxdelay - 2;
1598 	slot = (syncer_delayno + delay) & syncer_mask;
1599 
1600 	queue = VFS_NEEDSGIANT(bo->__bo_vnode->v_mount) ? WI_GIANTQ :
1601 	    WI_MPSAFEQ;
1602 	LIST_INSERT_HEAD(&syncer_workitem_pending[queue][slot], bo,
1603 	    bo_synclist);
1604 	mtx_unlock(&sync_mtx);
1605 }
1606 
1607 static int
1608 sysctl_vfs_worklist_len(SYSCTL_HANDLER_ARGS)
1609 {
1610 	int error, len;
1611 
1612 	mtx_lock(&sync_mtx);
1613 	len = syncer_worklist_len - sync_vnode_count;
1614 	mtx_unlock(&sync_mtx);
1615 	error = SYSCTL_OUT(req, &len, sizeof(len));
1616 	return (error);
1617 }
1618 
1619 SYSCTL_PROC(_vfs, OID_AUTO, worklist_len, CTLTYPE_INT | CTLFLAG_RD, NULL, 0,
1620     sysctl_vfs_worklist_len, "I", "Syncer thread worklist length");
1621 
1622 static struct proc *updateproc;
1623 static void sched_sync(void);
1624 static struct kproc_desc up_kp = {
1625 	"syncer",
1626 	sched_sync,
1627 	&updateproc
1628 };
1629 SYSINIT(syncer, SI_SUB_KTHREAD_UPDATE, SI_ORDER_FIRST, kproc_start, &up_kp);
1630 
1631 static int
1632 sync_vnode(struct synclist *slp, struct bufobj **bo, struct thread *td)
1633 {
1634 	struct vnode *vp;
1635 	struct mount *mp;
1636 
1637 	*bo = LIST_FIRST(slp);
1638 	if (*bo == NULL)
1639 		return (0);
1640 	vp = (*bo)->__bo_vnode;	/* XXX */
1641 	if (VOP_ISLOCKED(vp) != 0 || VI_TRYLOCK(vp) == 0)
1642 		return (1);
1643 	/*
1644 	 * We use vhold in case the vnode does not
1645 	 * successfully sync.  vhold prevents the vnode from
1646 	 * going away when we unlock the sync_mtx so that
1647 	 * we can acquire the vnode interlock.
1648 	 */
1649 	vholdl(vp);
1650 	mtx_unlock(&sync_mtx);
1651 	VI_UNLOCK(vp);
1652 	if (vn_start_write(vp, &mp, V_NOWAIT) != 0) {
1653 		vdrop(vp);
1654 		mtx_lock(&sync_mtx);
1655 		return (*bo == LIST_FIRST(slp));
1656 	}
1657 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
1658 	(void) VOP_FSYNC(vp, MNT_LAZY, td);
1659 	VOP_UNLOCK(vp, 0);
1660 	vn_finished_write(mp);
1661 	BO_LOCK(*bo);
1662 	if (((*bo)->bo_flag & BO_ONWORKLST) != 0) {
1663 		/*
1664 		 * Put us back on the worklist.  The worklist
1665 		 * routine will remove us from our current
1666 		 * position and then add us back in at a later
1667 		 * position.
1668 		 */
1669 		vn_syncer_add_to_worklist(*bo, syncdelay);
1670 	}
1671 	BO_UNLOCK(*bo);
1672 	vdrop(vp);
1673 	mtx_lock(&sync_mtx);
1674 	return (0);
1675 }
1676 
1677 /*
1678  * System filesystem synchronizer daemon.
1679  */
1680 static void
1681 sched_sync(void)
1682 {
1683 	struct synclist *gnext, *next;
1684 	struct synclist *gslp, *slp;
1685 	struct bufobj *bo;
1686 	long starttime;
1687 	struct thread *td = curthread;
1688 	int last_work_seen;
1689 	int net_worklist_len;
1690 	int syncer_final_iter;
1691 	int first_printf;
1692 	int error;
1693 
1694 	last_work_seen = 0;
1695 	syncer_final_iter = 0;
1696 	first_printf = 1;
1697 	syncer_state = SYNCER_RUNNING;
1698 	starttime = time_uptime;
1699 	td->td_pflags |= TDP_NORUNNINGBUF;
1700 
1701 	EVENTHANDLER_REGISTER(shutdown_pre_sync, syncer_shutdown, td->td_proc,
1702 	    SHUTDOWN_PRI_LAST);
1703 
1704 	mtx_lock(&sync_mtx);
1705 	for (;;) {
1706 		if (syncer_state == SYNCER_FINAL_DELAY &&
1707 		    syncer_final_iter == 0) {
1708 			mtx_unlock(&sync_mtx);
1709 			kproc_suspend_check(td->td_proc);
1710 			mtx_lock(&sync_mtx);
1711 		}
1712 		net_worklist_len = syncer_worklist_len - sync_vnode_count;
1713 		if (syncer_state != SYNCER_RUNNING &&
1714 		    starttime != time_uptime) {
1715 			if (first_printf) {
1716 				printf("\nSyncing disks, vnodes remaining...");
1717 				first_printf = 0;
1718 			}
1719 			printf("%d ", net_worklist_len);
1720 		}
1721 		starttime = time_uptime;
1722 
1723 		/*
1724 		 * Push files whose dirty time has expired.  Be careful
1725 		 * of interrupt race on slp queue.
1726 		 *
1727 		 * Skip over empty worklist slots when shutting down.
1728 		 */
1729 		do {
1730 			slp = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1731 			gslp = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1732 			syncer_delayno += 1;
1733 			if (syncer_delayno == syncer_maxdelay)
1734 				syncer_delayno = 0;
1735 			next = &syncer_workitem_pending[WI_MPSAFEQ][syncer_delayno];
1736 			gnext = &syncer_workitem_pending[WI_GIANTQ][syncer_delayno];
1737 			/*
1738 			 * If the worklist has wrapped since the
1739 			 * it was emptied of all but syncer vnodes,
1740 			 * switch to the FINAL_DELAY state and run
1741 			 * for one more second.
1742 			 */
1743 			if (syncer_state == SYNCER_SHUTTING_DOWN &&
1744 			    net_worklist_len == 0 &&
1745 			    last_work_seen == syncer_delayno) {
1746 				syncer_state = SYNCER_FINAL_DELAY;
1747 				syncer_final_iter = SYNCER_SHUTDOWN_SPEEDUP;
1748 			}
1749 		} while (syncer_state != SYNCER_RUNNING && LIST_EMPTY(slp) &&
1750 		    LIST_EMPTY(gslp) && syncer_worklist_len > 0);
1751 
1752 		/*
1753 		 * Keep track of the last time there was anything
1754 		 * on the worklist other than syncer vnodes.
1755 		 * Return to the SHUTTING_DOWN state if any
1756 		 * new work appears.
1757 		 */
1758 		if (net_worklist_len > 0 || syncer_state == SYNCER_RUNNING)
1759 			last_work_seen = syncer_delayno;
1760 		if (net_worklist_len > 0 && syncer_state == SYNCER_FINAL_DELAY)
1761 			syncer_state = SYNCER_SHUTTING_DOWN;
1762 		while (!LIST_EMPTY(slp)) {
1763 			error = sync_vnode(slp, &bo, td);
1764 			if (error == 1) {
1765 				LIST_REMOVE(bo, bo_synclist);
1766 				LIST_INSERT_HEAD(next, bo, bo_synclist);
1767 				continue;
1768 			}
1769 		}
1770 		if (!LIST_EMPTY(gslp)) {
1771 			mtx_unlock(&sync_mtx);
1772 			mtx_lock(&Giant);
1773 			mtx_lock(&sync_mtx);
1774 			while (!LIST_EMPTY(gslp)) {
1775 				error = sync_vnode(gslp, &bo, td);
1776 				if (error == 1) {
1777 					LIST_REMOVE(bo, bo_synclist);
1778 					LIST_INSERT_HEAD(gnext, bo,
1779 					    bo_synclist);
1780 					continue;
1781 				}
1782 			}
1783 			mtx_unlock(&Giant);
1784 		}
1785 		if (syncer_state == SYNCER_FINAL_DELAY && syncer_final_iter > 0)
1786 			syncer_final_iter--;
1787 		/*
1788 		 * The variable rushjob allows the kernel to speed up the
1789 		 * processing of the filesystem syncer process. A rushjob
1790 		 * value of N tells the filesystem syncer to process the next
1791 		 * N seconds worth of work on its queue ASAP. Currently rushjob
1792 		 * is used by the soft update code to speed up the filesystem
1793 		 * syncer process when the incore state is getting so far
1794 		 * ahead of the disk that the kernel memory pool is being
1795 		 * threatened with exhaustion.
1796 		 */
1797 		if (rushjob > 0) {
1798 			rushjob -= 1;
1799 			continue;
1800 		}
1801 		/*
1802 		 * Just sleep for a short period of time between
1803 		 * iterations when shutting down to allow some I/O
1804 		 * to happen.
1805 		 *
1806 		 * If it has taken us less than a second to process the
1807 		 * current work, then wait. Otherwise start right over
1808 		 * again. We can still lose time if any single round
1809 		 * takes more than two seconds, but it does not really
1810 		 * matter as we are just trying to generally pace the
1811 		 * filesystem activity.
1812 		 */
1813 		if (syncer_state != SYNCER_RUNNING)
1814 			cv_timedwait(&sync_wakeup, &sync_mtx,
1815 			    hz / SYNCER_SHUTDOWN_SPEEDUP);
1816 		else if (time_uptime == starttime)
1817 			cv_timedwait(&sync_wakeup, &sync_mtx, hz);
1818 	}
1819 }
1820 
1821 /*
1822  * Request the syncer daemon to speed up its work.
1823  * We never push it to speed up more than half of its
1824  * normal turn time, otherwise it could take over the cpu.
1825  */
1826 int
1827 speedup_syncer(void)
1828 {
1829 	int ret = 0;
1830 
1831 	mtx_lock(&sync_mtx);
1832 	if (rushjob < syncdelay / 2) {
1833 		rushjob += 1;
1834 		stat_rush_requests += 1;
1835 		ret = 1;
1836 	}
1837 	mtx_unlock(&sync_mtx);
1838 	cv_broadcast(&sync_wakeup);
1839 	return (ret);
1840 }
1841 
1842 /*
1843  * Tell the syncer to speed up its work and run though its work
1844  * list several times, then tell it to shut down.
1845  */
1846 static void
1847 syncer_shutdown(void *arg, int howto)
1848 {
1849 
1850 	if (howto & RB_NOSYNC)
1851 		return;
1852 	mtx_lock(&sync_mtx);
1853 	syncer_state = SYNCER_SHUTTING_DOWN;
1854 	rushjob = 0;
1855 	mtx_unlock(&sync_mtx);
1856 	cv_broadcast(&sync_wakeup);
1857 	kproc_shutdown(arg, howto);
1858 }
1859 
1860 /*
1861  * Reassign a buffer from one vnode to another.
1862  * Used to assign file specific control information
1863  * (indirect blocks) to the vnode to which they belong.
1864  */
1865 void
1866 reassignbuf(struct buf *bp)
1867 {
1868 	struct vnode *vp;
1869 	struct bufobj *bo;
1870 	int delay;
1871 #ifdef INVARIANTS
1872 	struct bufv *bv;
1873 #endif
1874 
1875 	vp = bp->b_vp;
1876 	bo = bp->b_bufobj;
1877 	++reassignbufcalls;
1878 
1879 	CTR3(KTR_BUF, "reassignbuf(%p) vp %p flags %X",
1880 	    bp, bp->b_vp, bp->b_flags);
1881 	/*
1882 	 * B_PAGING flagged buffers cannot be reassigned because their vp
1883 	 * is not fully linked in.
1884 	 */
1885 	if (bp->b_flags & B_PAGING)
1886 		panic("cannot reassign paging buffer");
1887 
1888 	/*
1889 	 * Delete from old vnode list, if on one.
1890 	 */
1891 	BO_LOCK(bo);
1892 	if (bp->b_xflags & (BX_VNDIRTY | BX_VNCLEAN))
1893 		buf_vlist_remove(bp);
1894 	else
1895 		panic("reassignbuf: Buffer %p not on queue.", bp);
1896 	/*
1897 	 * If dirty, put on list of dirty buffers; otherwise insert onto list
1898 	 * of clean buffers.
1899 	 */
1900 	if (bp->b_flags & B_DELWRI) {
1901 		if ((bo->bo_flag & BO_ONWORKLST) == 0) {
1902 			switch (vp->v_type) {
1903 			case VDIR:
1904 				delay = dirdelay;
1905 				break;
1906 			case VCHR:
1907 				delay = metadelay;
1908 				break;
1909 			default:
1910 				delay = filedelay;
1911 			}
1912 			vn_syncer_add_to_worklist(bo, delay);
1913 		}
1914 		buf_vlist_add(bp, bo, BX_VNDIRTY);
1915 	} else {
1916 		buf_vlist_add(bp, bo, BX_VNCLEAN);
1917 
1918 		if ((bo->bo_flag & BO_ONWORKLST) && bo->bo_dirty.bv_cnt == 0) {
1919 			mtx_lock(&sync_mtx);
1920 			LIST_REMOVE(bo, bo_synclist);
1921 			syncer_worklist_len--;
1922 			mtx_unlock(&sync_mtx);
1923 			bo->bo_flag &= ~BO_ONWORKLST;
1924 		}
1925 	}
1926 #ifdef INVARIANTS
1927 	bv = &bo->bo_clean;
1928 	bp = TAILQ_FIRST(&bv->bv_hd);
1929 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1930 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1931 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1932 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1933 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1934 	bv = &bo->bo_dirty;
1935 	bp = TAILQ_FIRST(&bv->bv_hd);
1936 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1937 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1938 	bp = TAILQ_LAST(&bv->bv_hd, buflists);
1939 	KASSERT(bp == NULL || bp->b_bufobj == bo,
1940 	    ("bp %p wrong b_bufobj %p should be %p", bp, bp->b_bufobj, bo));
1941 #endif
1942 	BO_UNLOCK(bo);
1943 }
1944 
1945 /*
1946  * Increment the use and hold counts on the vnode, taking care to reference
1947  * the driver's usecount if this is a chardev.  The vholdl() will remove
1948  * the vnode from the free list if it is presently free.  Requires the
1949  * vnode interlock and returns with it held.
1950  */
1951 static void
1952 v_incr_usecount(struct vnode *vp)
1953 {
1954 
1955 	CTR3(KTR_VFS, "v_incr_usecount: vp %p holdcnt %d usecount %d\n",
1956 	    vp, vp->v_holdcnt, vp->v_usecount);
1957 	vp->v_usecount++;
1958 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1959 		dev_lock();
1960 		vp->v_rdev->si_usecount++;
1961 		dev_unlock();
1962 	}
1963 	vholdl(vp);
1964 }
1965 
1966 /*
1967  * Turn a holdcnt into a use+holdcnt such that only one call to
1968  * v_decr_usecount is needed.
1969  */
1970 static void
1971 v_upgrade_usecount(struct vnode *vp)
1972 {
1973 
1974 	CTR3(KTR_VFS, "v_upgrade_usecount: vp %p holdcnt %d usecount %d\n",
1975 	    vp, vp->v_holdcnt, vp->v_usecount);
1976 	vp->v_usecount++;
1977 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
1978 		dev_lock();
1979 		vp->v_rdev->si_usecount++;
1980 		dev_unlock();
1981 	}
1982 }
1983 
1984 /*
1985  * Decrement the vnode use and hold count along with the driver's usecount
1986  * if this is a chardev.  The vdropl() below releases the vnode interlock
1987  * as it may free the vnode.
1988  */
1989 static void
1990 v_decr_usecount(struct vnode *vp)
1991 {
1992 
1993 	CTR3(KTR_VFS, "v_decr_usecount: vp %p holdcnt %d usecount %d\n",
1994 	    vp, vp->v_holdcnt, vp->v_usecount);
1995 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
1996 	VNASSERT(vp->v_usecount > 0, vp,
1997 	    ("v_decr_usecount: negative usecount"));
1998 	vp->v_usecount--;
1999 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2000 		dev_lock();
2001 		vp->v_rdev->si_usecount--;
2002 		dev_unlock();
2003 	}
2004 	vdropl(vp);
2005 }
2006 
2007 /*
2008  * Decrement only the use count and driver use count.  This is intended to
2009  * be paired with a follow on vdropl() to release the remaining hold count.
2010  * In this way we may vgone() a vnode with a 0 usecount without risk of
2011  * having it end up on a free list because the hold count is kept above 0.
2012  */
2013 static void
2014 v_decr_useonly(struct vnode *vp)
2015 {
2016 
2017 	CTR3(KTR_VFS, "v_decr_useonly: vp %p holdcnt %d usecount %d\n",
2018 	    vp, vp->v_holdcnt, vp->v_usecount);
2019 	ASSERT_VI_LOCKED(vp, __FUNCTION__);
2020 	VNASSERT(vp->v_usecount > 0, vp,
2021 	    ("v_decr_useonly: negative usecount"));
2022 	vp->v_usecount--;
2023 	if (vp->v_type == VCHR && vp->v_rdev != NULL) {
2024 		dev_lock();
2025 		vp->v_rdev->si_usecount--;
2026 		dev_unlock();
2027 	}
2028 }
2029 
2030 /*
2031  * Grab a particular vnode from the free list, increment its
2032  * reference count and lock it.  VI_DOOMED is set if the vnode
2033  * is being destroyed.  Only callers who specify LK_RETRY will
2034  * see doomed vnodes.  If inactive processing was delayed in
2035  * vput try to do it here.
2036  */
2037 int
2038 vget(struct vnode *vp, int flags, struct thread *td)
2039 {
2040 	int error;
2041 
2042 	error = 0;
2043 	VFS_ASSERT_GIANT(vp->v_mount);
2044 	VNASSERT((flags & LK_TYPE_MASK) != 0, vp,
2045 	    ("vget: invalid lock operation"));
2046 	if ((flags & LK_INTERLOCK) == 0)
2047 		VI_LOCK(vp);
2048 	vholdl(vp);
2049 	if ((error = vn_lock(vp, flags | LK_INTERLOCK)) != 0) {
2050 		vdrop(vp);
2051 		return (error);
2052 	}
2053 	if (vp->v_iflag & VI_DOOMED && (flags & LK_RETRY) == 0)
2054 		panic("vget: vn_lock failed to return ENOENT\n");
2055 	VI_LOCK(vp);
2056 	/* Upgrade our holdcnt to a usecount. */
2057 	v_upgrade_usecount(vp);
2058 	/*
2059  	 * We don't guarantee that any particular close will
2060 	 * trigger inactive processing so just make a best effort
2061 	 * here at preventing a reference to a removed file.  If
2062 	 * we don't succeed no harm is done.
2063 	 */
2064 	if (vp->v_iflag & VI_OWEINACT) {
2065 		if (VOP_ISLOCKED(vp) == LK_EXCLUSIVE &&
2066 		    (flags & LK_NOWAIT) == 0)
2067 			vinactive(vp, td);
2068 		vp->v_iflag &= ~VI_OWEINACT;
2069 	}
2070 	VI_UNLOCK(vp);
2071 	return (0);
2072 }
2073 
2074 /*
2075  * Increase the reference count of a vnode.
2076  */
2077 void
2078 vref(struct vnode *vp)
2079 {
2080 
2081 	VI_LOCK(vp);
2082 	v_incr_usecount(vp);
2083 	VI_UNLOCK(vp);
2084 }
2085 
2086 /*
2087  * Return reference count of a vnode.
2088  *
2089  * The results of this call are only guaranteed when some mechanism other
2090  * than the VI lock is used to stop other processes from gaining references
2091  * to the vnode.  This may be the case if the caller holds the only reference.
2092  * This is also useful when stale data is acceptable as race conditions may
2093  * be accounted for by some other means.
2094  */
2095 int
2096 vrefcnt(struct vnode *vp)
2097 {
2098 	int usecnt;
2099 
2100 	VI_LOCK(vp);
2101 	usecnt = vp->v_usecount;
2102 	VI_UNLOCK(vp);
2103 
2104 	return (usecnt);
2105 }
2106 
2107 
2108 /*
2109  * Vnode put/release.
2110  * If count drops to zero, call inactive routine and return to freelist.
2111  */
2112 void
2113 vrele(struct vnode *vp)
2114 {
2115 	struct thread *td = curthread;	/* XXX */
2116 
2117 	KASSERT(vp != NULL, ("vrele: null vp"));
2118 	VFS_ASSERT_GIANT(vp->v_mount);
2119 
2120 	VI_LOCK(vp);
2121 
2122 	/* Skip this v_writecount check if we're going to panic below. */
2123 	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2124 	    ("vrele: missed vn_close"));
2125 
2126 	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2127 	    vp->v_usecount == 1)) {
2128 		v_decr_usecount(vp);
2129 		return;
2130 	}
2131 	if (vp->v_usecount != 1) {
2132 #ifdef DIAGNOSTIC
2133 		vprint("vrele: negative ref count", vp);
2134 #endif
2135 		VI_UNLOCK(vp);
2136 		panic("vrele: negative ref cnt");
2137 	}
2138 	/*
2139 	 * We want to hold the vnode until the inactive finishes to
2140 	 * prevent vgone() races.  We drop the use count here and the
2141 	 * hold count below when we're done.
2142 	 */
2143 	v_decr_useonly(vp);
2144 	/*
2145 	 * We must call VOP_INACTIVE with the node locked. Mark
2146 	 * as VI_DOINGINACT to avoid recursion.
2147 	 */
2148 	vp->v_iflag |= VI_OWEINACT;
2149 	if (vn_lock(vp, LK_EXCLUSIVE | LK_INTERLOCK) == 0) {
2150 		VI_LOCK(vp);
2151 		if (vp->v_usecount > 0)
2152 			vp->v_iflag &= ~VI_OWEINACT;
2153 		if (vp->v_iflag & VI_OWEINACT)
2154 			vinactive(vp, td);
2155 		VOP_UNLOCK(vp, 0);
2156 	} else {
2157 		VI_LOCK(vp);
2158 		if (vp->v_usecount > 0)
2159 			vp->v_iflag &= ~VI_OWEINACT;
2160 	}
2161 	vdropl(vp);
2162 }
2163 
2164 /*
2165  * Release an already locked vnode.  This give the same effects as
2166  * unlock+vrele(), but takes less time and avoids releasing and
2167  * re-aquiring the lock (as vrele() acquires the lock internally.)
2168  */
2169 void
2170 vput(struct vnode *vp)
2171 {
2172 	struct thread *td = curthread;	/* XXX */
2173 	int error;
2174 
2175 	KASSERT(vp != NULL, ("vput: null vp"));
2176 	ASSERT_VOP_LOCKED(vp, "vput");
2177 	VFS_ASSERT_GIANT(vp->v_mount);
2178 	VI_LOCK(vp);
2179 	/* Skip this v_writecount check if we're going to panic below. */
2180 	VNASSERT(vp->v_writecount < vp->v_usecount || vp->v_usecount < 1, vp,
2181 	    ("vput: missed vn_close"));
2182 	error = 0;
2183 
2184 	if (vp->v_usecount > 1 || ((vp->v_iflag & VI_DOINGINACT) &&
2185 	    vp->v_usecount == 1)) {
2186 		VOP_UNLOCK(vp, 0);
2187 		v_decr_usecount(vp);
2188 		return;
2189 	}
2190 
2191 	if (vp->v_usecount != 1) {
2192 #ifdef DIAGNOSTIC
2193 		vprint("vput: negative ref count", vp);
2194 #endif
2195 		panic("vput: negative ref cnt");
2196 	}
2197 	/*
2198 	 * We want to hold the vnode until the inactive finishes to
2199 	 * prevent vgone() races.  We drop the use count here and the
2200 	 * hold count below when we're done.
2201 	 */
2202 	v_decr_useonly(vp);
2203 	vp->v_iflag |= VI_OWEINACT;
2204 	if (VOP_ISLOCKED(vp) != LK_EXCLUSIVE) {
2205 		error = VOP_LOCK(vp, LK_UPGRADE|LK_INTERLOCK|LK_NOWAIT);
2206 		VI_LOCK(vp);
2207 		if (error) {
2208 			if (vp->v_usecount > 0)
2209 				vp->v_iflag &= ~VI_OWEINACT;
2210 			goto done;
2211 		}
2212 	}
2213 	if (vp->v_usecount > 0)
2214 		vp->v_iflag &= ~VI_OWEINACT;
2215 	if (vp->v_iflag & VI_OWEINACT)
2216 		vinactive(vp, td);
2217 	VOP_UNLOCK(vp, 0);
2218 done:
2219 	vdropl(vp);
2220 }
2221 
2222 /*
2223  * Somebody doesn't want the vnode recycled.
2224  */
2225 void
2226 vhold(struct vnode *vp)
2227 {
2228 
2229 	VI_LOCK(vp);
2230 	vholdl(vp);
2231 	VI_UNLOCK(vp);
2232 }
2233 
2234 void
2235 vholdl(struct vnode *vp)
2236 {
2237 
2238 	vp->v_holdcnt++;
2239 	if (VSHOULDBUSY(vp))
2240 		vbusy(vp);
2241 }
2242 
2243 /*
2244  * Note that there is one less who cares about this vnode.  vdrop() is the
2245  * opposite of vhold().
2246  */
2247 void
2248 vdrop(struct vnode *vp)
2249 {
2250 
2251 	VI_LOCK(vp);
2252 	vdropl(vp);
2253 }
2254 
2255 /*
2256  * Drop the hold count of the vnode.  If this is the last reference to
2257  * the vnode we will free it if it has been vgone'd otherwise it is
2258  * placed on the free list.
2259  */
2260 void
2261 vdropl(struct vnode *vp)
2262 {
2263 
2264 	ASSERT_VI_LOCKED(vp, "vdropl");
2265 	if (vp->v_holdcnt <= 0)
2266 		panic("vdrop: holdcnt %d", vp->v_holdcnt);
2267 	vp->v_holdcnt--;
2268 	if (vp->v_holdcnt == 0) {
2269 		if (vp->v_iflag & VI_DOOMED) {
2270 			vdestroy(vp);
2271 			return;
2272 		} else
2273 			vfree(vp);
2274 	}
2275 	VI_UNLOCK(vp);
2276 }
2277 
2278 /*
2279  * Call VOP_INACTIVE on the vnode and manage the DOINGINACT and OWEINACT
2280  * flags.  DOINGINACT prevents us from recursing in calls to vinactive.
2281  * OWEINACT tracks whether a vnode missed a call to inactive due to a
2282  * failed lock upgrade.
2283  */
2284 static void
2285 vinactive(struct vnode *vp, struct thread *td)
2286 {
2287 
2288 	ASSERT_VOP_ELOCKED(vp, "vinactive");
2289 	ASSERT_VI_LOCKED(vp, "vinactive");
2290 	VNASSERT((vp->v_iflag & VI_DOINGINACT) == 0, vp,
2291 	    ("vinactive: recursed on VI_DOINGINACT"));
2292 	vp->v_iflag |= VI_DOINGINACT;
2293 	vp->v_iflag &= ~VI_OWEINACT;
2294 	VI_UNLOCK(vp);
2295 	VOP_INACTIVE(vp, td);
2296 	VI_LOCK(vp);
2297 	VNASSERT(vp->v_iflag & VI_DOINGINACT, vp,
2298 	    ("vinactive: lost VI_DOINGINACT"));
2299 	vp->v_iflag &= ~VI_DOINGINACT;
2300 }
2301 
2302 /*
2303  * Remove any vnodes in the vnode table belonging to mount point mp.
2304  *
2305  * If FORCECLOSE is not specified, there should not be any active ones,
2306  * return error if any are found (nb: this is a user error, not a
2307  * system error). If FORCECLOSE is specified, detach any active vnodes
2308  * that are found.
2309  *
2310  * If WRITECLOSE is set, only flush out regular file vnodes open for
2311  * writing.
2312  *
2313  * SKIPSYSTEM causes any vnodes marked VV_SYSTEM to be skipped.
2314  *
2315  * `rootrefs' specifies the base reference count for the root vnode
2316  * of this filesystem. The root vnode is considered busy if its
2317  * v_usecount exceeds this value. On a successful return, vflush(, td)
2318  * will call vrele() on the root vnode exactly rootrefs times.
2319  * If the SKIPSYSTEM or WRITECLOSE flags are specified, rootrefs must
2320  * be zero.
2321  */
2322 #ifdef DIAGNOSTIC
2323 static int busyprt = 0;		/* print out busy vnodes */
2324 SYSCTL_INT(_debug, OID_AUTO, busyprt, CTLFLAG_RW, &busyprt, 0, "");
2325 #endif
2326 
2327 int
2328 vflush( struct mount *mp, int rootrefs, int flags, struct thread *td)
2329 {
2330 	struct vnode *vp, *mvp, *rootvp = NULL;
2331 	struct vattr vattr;
2332 	int busy = 0, error;
2333 
2334 	CTR1(KTR_VFS, "vflush: mp %p", mp);
2335 	if (rootrefs > 0) {
2336 		KASSERT((flags & (SKIPSYSTEM | WRITECLOSE)) == 0,
2337 		    ("vflush: bad args"));
2338 		/*
2339 		 * Get the filesystem root vnode. We can vput() it
2340 		 * immediately, since with rootrefs > 0, it won't go away.
2341 		 */
2342 		if ((error = VFS_ROOT(mp, LK_EXCLUSIVE, &rootvp, td)) != 0)
2343 			return (error);
2344 		vput(rootvp);
2345 
2346 	}
2347 	MNT_ILOCK(mp);
2348 loop:
2349 	MNT_VNODE_FOREACH(vp, mp, mvp) {
2350 
2351 		VI_LOCK(vp);
2352 		vholdl(vp);
2353 		MNT_IUNLOCK(mp);
2354 		error = vn_lock(vp, LK_INTERLOCK | LK_EXCLUSIVE);
2355 		if (error) {
2356 			vdrop(vp);
2357 			MNT_ILOCK(mp);
2358 			MNT_VNODE_FOREACH_ABORT_ILOCKED(mp, mvp);
2359 			goto loop;
2360 		}
2361 		/*
2362 		 * Skip over a vnodes marked VV_SYSTEM.
2363 		 */
2364 		if ((flags & SKIPSYSTEM) && (vp->v_vflag & VV_SYSTEM)) {
2365 			VOP_UNLOCK(vp, 0);
2366 			vdrop(vp);
2367 			MNT_ILOCK(mp);
2368 			continue;
2369 		}
2370 		/*
2371 		 * If WRITECLOSE is set, flush out unlinked but still open
2372 		 * files (even if open only for reading) and regular file
2373 		 * vnodes open for writing.
2374 		 */
2375 		if (flags & WRITECLOSE) {
2376 			error = VOP_GETATTR(vp, &vattr, td->td_ucred);
2377 			VI_LOCK(vp);
2378 
2379 			if ((vp->v_type == VNON ||
2380 			    (error == 0 && vattr.va_nlink > 0)) &&
2381 			    (vp->v_writecount == 0 || vp->v_type != VREG)) {
2382 				VOP_UNLOCK(vp, 0);
2383 				vdropl(vp);
2384 				MNT_ILOCK(mp);
2385 				continue;
2386 			}
2387 		} else
2388 			VI_LOCK(vp);
2389 		/*
2390 		 * With v_usecount == 0, all we need to do is clear out the
2391 		 * vnode data structures and we are done.
2392 		 *
2393 		 * If FORCECLOSE is set, forcibly close the vnode.
2394 		 */
2395 		if (vp->v_usecount == 0 || (flags & FORCECLOSE)) {
2396 			VNASSERT(vp->v_usecount == 0 ||
2397 			    (vp->v_type != VCHR && vp->v_type != VBLK), vp,
2398 			    ("device VNODE %p is FORCECLOSED", vp));
2399 			vgonel(vp);
2400 		} else {
2401 			busy++;
2402 #ifdef DIAGNOSTIC
2403 			if (busyprt)
2404 				vprint("vflush: busy vnode", vp);
2405 #endif
2406 		}
2407 		VOP_UNLOCK(vp, 0);
2408 		vdropl(vp);
2409 		MNT_ILOCK(mp);
2410 	}
2411 	MNT_IUNLOCK(mp);
2412 	if (rootrefs > 0 && (flags & FORCECLOSE) == 0) {
2413 		/*
2414 		 * If just the root vnode is busy, and if its refcount
2415 		 * is equal to `rootrefs', then go ahead and kill it.
2416 		 */
2417 		VI_LOCK(rootvp);
2418 		KASSERT(busy > 0, ("vflush: not busy"));
2419 		VNASSERT(rootvp->v_usecount >= rootrefs, rootvp,
2420 		    ("vflush: usecount %d < rootrefs %d",
2421 		     rootvp->v_usecount, rootrefs));
2422 		if (busy == 1 && rootvp->v_usecount == rootrefs) {
2423 			VOP_LOCK(rootvp, LK_EXCLUSIVE|LK_INTERLOCK);
2424 			vgone(rootvp);
2425 			VOP_UNLOCK(rootvp, 0);
2426 			busy = 0;
2427 		} else
2428 			VI_UNLOCK(rootvp);
2429 	}
2430 	if (busy)
2431 		return (EBUSY);
2432 	for (; rootrefs > 0; rootrefs--)
2433 		vrele(rootvp);
2434 	return (0);
2435 }
2436 
2437 /*
2438  * Recycle an unused vnode to the front of the free list.
2439  */
2440 int
2441 vrecycle(struct vnode *vp, struct thread *td)
2442 {
2443 	int recycled;
2444 
2445 	ASSERT_VOP_ELOCKED(vp, "vrecycle");
2446 	recycled = 0;
2447 	VI_LOCK(vp);
2448 	if (vp->v_usecount == 0) {
2449 		recycled = 1;
2450 		vgonel(vp);
2451 	}
2452 	VI_UNLOCK(vp);
2453 	return (recycled);
2454 }
2455 
2456 /*
2457  * Eliminate all activity associated with a vnode
2458  * in preparation for reuse.
2459  */
2460 void
2461 vgone(struct vnode *vp)
2462 {
2463 	VI_LOCK(vp);
2464 	vgonel(vp);
2465 	VI_UNLOCK(vp);
2466 }
2467 
2468 /*
2469  * vgone, with the vp interlock held.
2470  */
2471 void
2472 vgonel(struct vnode *vp)
2473 {
2474 	struct thread *td;
2475 	int oweinact;
2476 	int active;
2477 	struct mount *mp;
2478 
2479 	CTR1(KTR_VFS, "vgonel: vp %p", vp);
2480 	ASSERT_VOP_ELOCKED(vp, "vgonel");
2481 	ASSERT_VI_LOCKED(vp, "vgonel");
2482 	VNASSERT(vp->v_holdcnt, vp,
2483 	    ("vgonel: vp %p has no reference.", vp));
2484 	td = curthread;
2485 
2486 	/*
2487 	 * Don't vgonel if we're already doomed.
2488 	 */
2489 	if (vp->v_iflag & VI_DOOMED)
2490 		return;
2491 	vp->v_iflag |= VI_DOOMED;
2492 	/*
2493 	 * Check to see if the vnode is in use.  If so, we have to call
2494 	 * VOP_CLOSE() and VOP_INACTIVE().
2495 	 */
2496 	active = vp->v_usecount;
2497 	oweinact = (vp->v_iflag & VI_OWEINACT);
2498 	VI_UNLOCK(vp);
2499 	/*
2500 	 * Clean out any buffers associated with the vnode.
2501 	 * If the flush fails, just toss the buffers.
2502 	 */
2503 	mp = NULL;
2504 	if (!TAILQ_EMPTY(&vp->v_bufobj.bo_dirty.bv_hd))
2505 		(void) vn_start_secondary_write(vp, &mp, V_WAIT);
2506 	if (vinvalbuf(vp, V_SAVE, 0, 0) != 0)
2507 		vinvalbuf(vp, 0, 0, 0);
2508 
2509 	/*
2510 	 * If purging an active vnode, it must be closed and
2511 	 * deactivated before being reclaimed.
2512 	 */
2513 	if (active)
2514 		VOP_CLOSE(vp, FNONBLOCK, NOCRED, td);
2515 	if (oweinact || active) {
2516 		VI_LOCK(vp);
2517 		if ((vp->v_iflag & VI_DOINGINACT) == 0)
2518 			vinactive(vp, td);
2519 		VI_UNLOCK(vp);
2520 	}
2521 	/*
2522 	 * Reclaim the vnode.
2523 	 */
2524 	if (VOP_RECLAIM(vp, td))
2525 		panic("vgone: cannot reclaim");
2526 	if (mp != NULL)
2527 		vn_finished_secondary_write(mp);
2528 	VNASSERT(vp->v_object == NULL, vp,
2529 	    ("vop_reclaim left v_object vp=%p, tag=%s", vp, vp->v_tag));
2530 	/*
2531 	 * Clear the advisory locks and wake up waiting threads.
2532 	 */
2533 	lf_purgelocks(vp, &(vp->v_lockf));
2534 	/*
2535 	 * Delete from old mount point vnode list.
2536 	 */
2537 	delmntque(vp);
2538 	cache_purge(vp);
2539 	/*
2540 	 * Done with purge, reset to the standard lock and invalidate
2541 	 * the vnode.
2542 	 */
2543 	VI_LOCK(vp);
2544 	vp->v_vnlock = &vp->v_lock;
2545 	vp->v_op = &dead_vnodeops;
2546 	vp->v_tag = "none";
2547 	vp->v_type = VBAD;
2548 }
2549 
2550 /*
2551  * Calculate the total number of references to a special device.
2552  */
2553 int
2554 vcount(struct vnode *vp)
2555 {
2556 	int count;
2557 
2558 	dev_lock();
2559 	count = vp->v_rdev->si_usecount;
2560 	dev_unlock();
2561 	return (count);
2562 }
2563 
2564 /*
2565  * Same as above, but using the struct cdev *as argument
2566  */
2567 int
2568 count_dev(struct cdev *dev)
2569 {
2570 	int count;
2571 
2572 	dev_lock();
2573 	count = dev->si_usecount;
2574 	dev_unlock();
2575 	return(count);
2576 }
2577 
2578 /*
2579  * Print out a description of a vnode.
2580  */
2581 static char *typename[] =
2582 {"VNON", "VREG", "VDIR", "VBLK", "VCHR", "VLNK", "VSOCK", "VFIFO", "VBAD",
2583  "VMARKER"};
2584 
2585 void
2586 vn_printf(struct vnode *vp, const char *fmt, ...)
2587 {
2588 	va_list ap;
2589 	char buf[256], buf2[16];
2590 	u_long flags;
2591 
2592 	va_start(ap, fmt);
2593 	vprintf(fmt, ap);
2594 	va_end(ap);
2595 	printf("%p: ", (void *)vp);
2596 	printf("tag %s, type %s\n", vp->v_tag, typename[vp->v_type]);
2597 	printf("    usecount %d, writecount %d, refcount %d mountedhere %p\n",
2598 	    vp->v_usecount, vp->v_writecount, vp->v_holdcnt, vp->v_mountedhere);
2599 	buf[0] = '\0';
2600 	buf[1] = '\0';
2601 	if (vp->v_vflag & VV_ROOT)
2602 		strlcat(buf, "|VV_ROOT", sizeof(buf));
2603 	if (vp->v_vflag & VV_ISTTY)
2604 		strlcat(buf, "|VV_ISTTY", sizeof(buf));
2605 	if (vp->v_vflag & VV_NOSYNC)
2606 		strlcat(buf, "|VV_NOSYNC", sizeof(buf));
2607 	if (vp->v_vflag & VV_CACHEDLABEL)
2608 		strlcat(buf, "|VV_CACHEDLABEL", sizeof(buf));
2609 	if (vp->v_vflag & VV_TEXT)
2610 		strlcat(buf, "|VV_TEXT", sizeof(buf));
2611 	if (vp->v_vflag & VV_COPYONWRITE)
2612 		strlcat(buf, "|VV_COPYONWRITE", sizeof(buf));
2613 	if (vp->v_vflag & VV_SYSTEM)
2614 		strlcat(buf, "|VV_SYSTEM", sizeof(buf));
2615 	if (vp->v_vflag & VV_PROCDEP)
2616 		strlcat(buf, "|VV_PROCDEP", sizeof(buf));
2617 	if (vp->v_vflag & VV_NOKNOTE)
2618 		strlcat(buf, "|VV_NOKNOTE", sizeof(buf));
2619 	if (vp->v_vflag & VV_DELETED)
2620 		strlcat(buf, "|VV_DELETED", sizeof(buf));
2621 	if (vp->v_vflag & VV_MD)
2622 		strlcat(buf, "|VV_MD", sizeof(buf));
2623 	flags = vp->v_vflag & ~(VV_ROOT | VV_ISTTY | VV_NOSYNC |
2624 	    VV_CACHEDLABEL | VV_TEXT | VV_COPYONWRITE | VV_SYSTEM | VV_PROCDEP |
2625 	    VV_NOKNOTE | VV_DELETED | VV_MD);
2626 	if (flags != 0) {
2627 		snprintf(buf2, sizeof(buf2), "|VV(0x%lx)", flags);
2628 		strlcat(buf, buf2, sizeof(buf));
2629 	}
2630 	if (vp->v_iflag & VI_MOUNT)
2631 		strlcat(buf, "|VI_MOUNT", sizeof(buf));
2632 	if (vp->v_iflag & VI_AGE)
2633 		strlcat(buf, "|VI_AGE", sizeof(buf));
2634 	if (vp->v_iflag & VI_DOOMED)
2635 		strlcat(buf, "|VI_DOOMED", sizeof(buf));
2636 	if (vp->v_iflag & VI_FREE)
2637 		strlcat(buf, "|VI_FREE", sizeof(buf));
2638 	if (vp->v_iflag & VI_OBJDIRTY)
2639 		strlcat(buf, "|VI_OBJDIRTY", sizeof(buf));
2640 	if (vp->v_iflag & VI_DOINGINACT)
2641 		strlcat(buf, "|VI_DOINGINACT", sizeof(buf));
2642 	if (vp->v_iflag & VI_OWEINACT)
2643 		strlcat(buf, "|VI_OWEINACT", sizeof(buf));
2644 	flags = vp->v_iflag & ~(VI_MOUNT | VI_AGE | VI_DOOMED | VI_FREE |
2645 	    VI_OBJDIRTY | VI_DOINGINACT | VI_OWEINACT);
2646 	if (flags != 0) {
2647 		snprintf(buf2, sizeof(buf2), "|VI(0x%lx)", flags);
2648 		strlcat(buf, buf2, sizeof(buf));
2649 	}
2650 	printf("    flags (%s)\n", buf + 1);
2651 	if (mtx_owned(VI_MTX(vp)))
2652 		printf(" VI_LOCKed");
2653 	if (vp->v_object != NULL)
2654 		printf("    v_object %p ref %d pages %d\n",
2655 		    vp->v_object, vp->v_object->ref_count,
2656 		    vp->v_object->resident_page_count);
2657 	printf("    ");
2658 	lockmgr_printinfo(vp->v_vnlock);
2659 	printf("\n");
2660 	if (vp->v_data != NULL)
2661 		VOP_PRINT(vp);
2662 }
2663 
2664 #ifdef DDB
2665 /*
2666  * List all of the locked vnodes in the system.
2667  * Called when debugging the kernel.
2668  */
2669 DB_SHOW_COMMAND(lockedvnods, lockedvnodes)
2670 {
2671 	struct mount *mp, *nmp;
2672 	struct vnode *vp;
2673 
2674 	/*
2675 	 * Note: because this is DDB, we can't obey the locking semantics
2676 	 * for these structures, which means we could catch an inconsistent
2677 	 * state and dereference a nasty pointer.  Not much to be done
2678 	 * about that.
2679 	 */
2680 	db_printf("Locked vnodes\n");
2681 	for (mp = TAILQ_FIRST(&mountlist); mp != NULL; mp = nmp) {
2682 		nmp = TAILQ_NEXT(mp, mnt_list);
2683 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2684 			if (vp->v_type != VMARKER &&
2685 			    VOP_ISLOCKED(vp))
2686 				vprint("", vp);
2687 		}
2688 		nmp = TAILQ_NEXT(mp, mnt_list);
2689 	}
2690 }
2691 
2692 /*
2693  * Show details about the given vnode.
2694  */
2695 DB_SHOW_COMMAND(vnode, db_show_vnode)
2696 {
2697 	struct vnode *vp;
2698 
2699 	if (!have_addr)
2700 		return;
2701 	vp = (struct vnode *)addr;
2702 	vn_printf(vp, "vnode ");
2703 }
2704 
2705 /*
2706  * Show details about the given mount point.
2707  */
2708 DB_SHOW_COMMAND(mount, db_show_mount)
2709 {
2710 	struct mount *mp;
2711 	struct statfs *sp;
2712 	struct vnode *vp;
2713 	char buf[512];
2714 	u_int flags;
2715 
2716 	if (!have_addr) {
2717 		/* No address given, print short info about all mount points. */
2718 		TAILQ_FOREACH(mp, &mountlist, mnt_list) {
2719 			db_printf("%p %s on %s (%s)\n", mp,
2720 			    mp->mnt_stat.f_mntfromname,
2721 			    mp->mnt_stat.f_mntonname,
2722 			    mp->mnt_stat.f_fstypename);
2723 			if (db_pager_quit)
2724 				break;
2725 		}
2726 		db_printf("\nMore info: show mount <addr>\n");
2727 		return;
2728 	}
2729 
2730 	mp = (struct mount *)addr;
2731 	db_printf("%p %s on %s (%s)\n", mp, mp->mnt_stat.f_mntfromname,
2732 	    mp->mnt_stat.f_mntonname, mp->mnt_stat.f_fstypename);
2733 
2734 	buf[0] = '\0';
2735 	flags = mp->mnt_flag;
2736 #define	MNT_FLAG(flag)	do {						\
2737 	if (flags & (flag)) {						\
2738 		if (buf[0] != '\0')					\
2739 			strlcat(buf, ", ", sizeof(buf));		\
2740 		strlcat(buf, (#flag) + 4, sizeof(buf));			\
2741 		flags &= ~(flag);					\
2742 	}								\
2743 } while (0)
2744 	MNT_FLAG(MNT_RDONLY);
2745 	MNT_FLAG(MNT_SYNCHRONOUS);
2746 	MNT_FLAG(MNT_NOEXEC);
2747 	MNT_FLAG(MNT_NOSUID);
2748 	MNT_FLAG(MNT_UNION);
2749 	MNT_FLAG(MNT_ASYNC);
2750 	MNT_FLAG(MNT_SUIDDIR);
2751 	MNT_FLAG(MNT_SOFTDEP);
2752 	MNT_FLAG(MNT_NOSYMFOLLOW);
2753 	MNT_FLAG(MNT_GJOURNAL);
2754 	MNT_FLAG(MNT_MULTILABEL);
2755 	MNT_FLAG(MNT_ACLS);
2756 	MNT_FLAG(MNT_NOATIME);
2757 	MNT_FLAG(MNT_NOCLUSTERR);
2758 	MNT_FLAG(MNT_NOCLUSTERW);
2759 	MNT_FLAG(MNT_EXRDONLY);
2760 	MNT_FLAG(MNT_EXPORTED);
2761 	MNT_FLAG(MNT_DEFEXPORTED);
2762 	MNT_FLAG(MNT_EXPORTANON);
2763 	MNT_FLAG(MNT_EXKERB);
2764 	MNT_FLAG(MNT_EXPUBLIC);
2765 	MNT_FLAG(MNT_LOCAL);
2766 	MNT_FLAG(MNT_QUOTA);
2767 	MNT_FLAG(MNT_ROOTFS);
2768 	MNT_FLAG(MNT_USER);
2769 	MNT_FLAG(MNT_IGNORE);
2770 	MNT_FLAG(MNT_UPDATE);
2771 	MNT_FLAG(MNT_DELEXPORT);
2772 	MNT_FLAG(MNT_RELOAD);
2773 	MNT_FLAG(MNT_FORCE);
2774 	MNT_FLAG(MNT_SNAPSHOT);
2775 	MNT_FLAG(MNT_BYFSID);
2776 #undef MNT_FLAG
2777 	if (flags != 0) {
2778 		if (buf[0] != '\0')
2779 			strlcat(buf, ", ", sizeof(buf));
2780 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2781 		    "0x%08x", flags);
2782 	}
2783 	db_printf("    mnt_flag = %s\n", buf);
2784 
2785 	buf[0] = '\0';
2786 	flags = mp->mnt_kern_flag;
2787 #define	MNT_KERN_FLAG(flag)	do {					\
2788 	if (flags & (flag)) {						\
2789 		if (buf[0] != '\0')					\
2790 			strlcat(buf, ", ", sizeof(buf));		\
2791 		strlcat(buf, (#flag) + 5, sizeof(buf));			\
2792 		flags &= ~(flag);					\
2793 	}								\
2794 } while (0)
2795 	MNT_KERN_FLAG(MNTK_UNMOUNTF);
2796 	MNT_KERN_FLAG(MNTK_ASYNC);
2797 	MNT_KERN_FLAG(MNTK_SOFTDEP);
2798 	MNT_KERN_FLAG(MNTK_NOINSMNTQ);
2799 	MNT_KERN_FLAG(MNTK_UNMOUNT);
2800 	MNT_KERN_FLAG(MNTK_MWAIT);
2801 	MNT_KERN_FLAG(MNTK_SUSPEND);
2802 	MNT_KERN_FLAG(MNTK_SUSPEND2);
2803 	MNT_KERN_FLAG(MNTK_SUSPENDED);
2804 	MNT_KERN_FLAG(MNTK_MPSAFE);
2805 	MNT_KERN_FLAG(MNTK_NOKNOTE);
2806 	MNT_KERN_FLAG(MNTK_LOOKUP_SHARED);
2807 #undef MNT_KERN_FLAG
2808 	if (flags != 0) {
2809 		if (buf[0] != '\0')
2810 			strlcat(buf, ", ", sizeof(buf));
2811 		snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
2812 		    "0x%08x", flags);
2813 	}
2814 	db_printf("    mnt_kern_flag = %s\n", buf);
2815 
2816 	sp = &mp->mnt_stat;
2817 	db_printf("    mnt_stat = { version=%u type=%u flags=0x%016jx "
2818 	    "bsize=%ju iosize=%ju blocks=%ju bfree=%ju bavail=%jd files=%ju "
2819 	    "ffree=%jd syncwrites=%ju asyncwrites=%ju syncreads=%ju "
2820 	    "asyncreads=%ju namemax=%u owner=%u fsid=[%d, %d] }\n",
2821 	    (u_int)sp->f_version, (u_int)sp->f_type, (uintmax_t)sp->f_flags,
2822 	    (uintmax_t)sp->f_bsize, (uintmax_t)sp->f_iosize,
2823 	    (uintmax_t)sp->f_blocks, (uintmax_t)sp->f_bfree,
2824 	    (intmax_t)sp->f_bavail, (uintmax_t)sp->f_files,
2825 	    (intmax_t)sp->f_ffree, (uintmax_t)sp->f_syncwrites,
2826 	    (uintmax_t)sp->f_asyncwrites, (uintmax_t)sp->f_syncreads,
2827 	    (uintmax_t)sp->f_asyncreads, (u_int)sp->f_namemax,
2828 	    (u_int)sp->f_owner, (int)sp->f_fsid.val[0], (int)sp->f_fsid.val[1]);
2829 
2830 	db_printf("    mnt_cred = { uid=%u ruid=%u",
2831 	    (u_int)mp->mnt_cred->cr_uid, (u_int)mp->mnt_cred->cr_ruid);
2832 	if (mp->mnt_cred->cr_prison != NULL)
2833 		db_printf(", jail=%d", mp->mnt_cred->cr_prison->pr_id);
2834 	db_printf(" }\n");
2835 	db_printf("    mnt_ref = %d\n", mp->mnt_ref);
2836 	db_printf("    mnt_gen = %d\n", mp->mnt_gen);
2837 	db_printf("    mnt_nvnodelistsize = %d\n", mp->mnt_nvnodelistsize);
2838 	db_printf("    mnt_writeopcount = %d\n", mp->mnt_writeopcount);
2839 	db_printf("    mnt_noasync = %u\n", mp->mnt_noasync);
2840 	db_printf("    mnt_maxsymlinklen = %d\n", mp->mnt_maxsymlinklen);
2841 	db_printf("    mnt_iosize_max = %d\n", mp->mnt_iosize_max);
2842 	db_printf("    mnt_hashseed = %u\n", mp->mnt_hashseed);
2843 	db_printf("    mnt_markercnt = %d\n", mp->mnt_markercnt);
2844 	db_printf("    mnt_holdcnt = %d\n", mp->mnt_holdcnt);
2845 	db_printf("    mnt_holdcntwaiters = %d\n", mp->mnt_holdcntwaiters);
2846 	db_printf("    mnt_secondary_writes = %d\n", mp->mnt_secondary_writes);
2847 	db_printf("    mnt_secondary_accwrites = %d\n",
2848 	    mp->mnt_secondary_accwrites);
2849 	db_printf("    mnt_gjprovider = %s\n",
2850 	    mp->mnt_gjprovider != NULL ? mp->mnt_gjprovider : "NULL");
2851 	db_printf("\n");
2852 
2853 	TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
2854 		if (vp->v_type != VMARKER) {
2855 			vn_printf(vp, "vnode ");
2856 			if (db_pager_quit)
2857 				break;
2858 		}
2859 	}
2860 }
2861 #endif	/* DDB */
2862 
2863 /*
2864  * Fill in a struct xvfsconf based on a struct vfsconf.
2865  */
2866 static void
2867 vfsconf2x(struct vfsconf *vfsp, struct xvfsconf *xvfsp)
2868 {
2869 
2870 	strcpy(xvfsp->vfc_name, vfsp->vfc_name);
2871 	xvfsp->vfc_typenum = vfsp->vfc_typenum;
2872 	xvfsp->vfc_refcount = vfsp->vfc_refcount;
2873 	xvfsp->vfc_flags = vfsp->vfc_flags;
2874 	/*
2875 	 * These are unused in userland, we keep them
2876 	 * to not break binary compatibility.
2877 	 */
2878 	xvfsp->vfc_vfsops = NULL;
2879 	xvfsp->vfc_next = NULL;
2880 }
2881 
2882 /*
2883  * Top level filesystem related information gathering.
2884  */
2885 static int
2886 sysctl_vfs_conflist(SYSCTL_HANDLER_ARGS)
2887 {
2888 	struct vfsconf *vfsp;
2889 	struct xvfsconf xvfsp;
2890 	int error;
2891 
2892 	error = 0;
2893 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2894 		bzero(&xvfsp, sizeof(xvfsp));
2895 		vfsconf2x(vfsp, &xvfsp);
2896 		error = SYSCTL_OUT(req, &xvfsp, sizeof xvfsp);
2897 		if (error)
2898 			break;
2899 	}
2900 	return (error);
2901 }
2902 
2903 SYSCTL_PROC(_vfs, OID_AUTO, conflist, CTLFLAG_RD, NULL, 0, sysctl_vfs_conflist,
2904     "S,xvfsconf", "List of all configured filesystems");
2905 
2906 #ifndef BURN_BRIDGES
2907 static int	sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS);
2908 
2909 static int
2910 vfs_sysctl(SYSCTL_HANDLER_ARGS)
2911 {
2912 	int *name = (int *)arg1 - 1;	/* XXX */
2913 	u_int namelen = arg2 + 1;	/* XXX */
2914 	struct vfsconf *vfsp;
2915 	struct xvfsconf xvfsp;
2916 
2917 	printf("WARNING: userland calling deprecated sysctl, "
2918 	    "please rebuild world\n");
2919 
2920 #if 1 || defined(COMPAT_PRELITE2)
2921 	/* Resolve ambiguity between VFS_VFSCONF and VFS_GENERIC. */
2922 	if (namelen == 1)
2923 		return (sysctl_ovfs_conf(oidp, arg1, arg2, req));
2924 #endif
2925 
2926 	switch (name[1]) {
2927 	case VFS_MAXTYPENUM:
2928 		if (namelen != 2)
2929 			return (ENOTDIR);
2930 		return (SYSCTL_OUT(req, &maxvfsconf, sizeof(int)));
2931 	case VFS_CONF:
2932 		if (namelen != 3)
2933 			return (ENOTDIR);	/* overloaded */
2934 		TAILQ_FOREACH(vfsp, &vfsconf, vfc_list)
2935 			if (vfsp->vfc_typenum == name[2])
2936 				break;
2937 		if (vfsp == NULL)
2938 			return (EOPNOTSUPP);
2939 		bzero(&xvfsp, sizeof(xvfsp));
2940 		vfsconf2x(vfsp, &xvfsp);
2941 		return (SYSCTL_OUT(req, &xvfsp, sizeof(xvfsp)));
2942 	}
2943 	return (EOPNOTSUPP);
2944 }
2945 
2946 static SYSCTL_NODE(_vfs, VFS_GENERIC, generic, CTLFLAG_RD | CTLFLAG_SKIP,
2947 	vfs_sysctl, "Generic filesystem");
2948 
2949 #if 1 || defined(COMPAT_PRELITE2)
2950 
2951 static int
2952 sysctl_ovfs_conf(SYSCTL_HANDLER_ARGS)
2953 {
2954 	int error;
2955 	struct vfsconf *vfsp;
2956 	struct ovfsconf ovfs;
2957 
2958 	TAILQ_FOREACH(vfsp, &vfsconf, vfc_list) {
2959 		bzero(&ovfs, sizeof(ovfs));
2960 		ovfs.vfc_vfsops = vfsp->vfc_vfsops;	/* XXX used as flag */
2961 		strcpy(ovfs.vfc_name, vfsp->vfc_name);
2962 		ovfs.vfc_index = vfsp->vfc_typenum;
2963 		ovfs.vfc_refcount = vfsp->vfc_refcount;
2964 		ovfs.vfc_flags = vfsp->vfc_flags;
2965 		error = SYSCTL_OUT(req, &ovfs, sizeof ovfs);
2966 		if (error)
2967 			return error;
2968 	}
2969 	return 0;
2970 }
2971 
2972 #endif /* 1 || COMPAT_PRELITE2 */
2973 #endif /* !BURN_BRIDGES */
2974 
2975 #define KINFO_VNODESLOP		10
2976 #ifdef notyet
2977 /*
2978  * Dump vnode list (via sysctl).
2979  */
2980 /* ARGSUSED */
2981 static int
2982 sysctl_vnode(SYSCTL_HANDLER_ARGS)
2983 {
2984 	struct xvnode *xvn;
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 	error = sysctl_wire_old_buffer(req, 0);
2999 	if (error != 0)
3000 		return (error);
3001 	xvn = malloc(len, M_TEMP, M_ZERO | M_WAITOK);
3002 	n = 0;
3003 	mtx_lock(&mountlist_mtx);
3004 	TAILQ_FOREACH(mp, &mountlist, mnt_list) {
3005 		if (vfs_busy(mp, LK_NOWAIT, &mountlist_mtx))
3006 			continue;
3007 		MNT_ILOCK(mp);
3008 		TAILQ_FOREACH(vp, &mp->mnt_nvnodelist, v_nmntvnodes) {
3009 			if (n == len)
3010 				break;
3011 			vref(vp);
3012 			xvn[n].xv_size = sizeof *xvn;
3013 			xvn[n].xv_vnode = vp;
3014 			xvn[n].xv_id = 0;	/* XXX compat */
3015 #define XV_COPY(field) xvn[n].xv_##field = vp->v_##field
3016 			XV_COPY(usecount);
3017 			XV_COPY(writecount);
3018 			XV_COPY(holdcnt);
3019 			XV_COPY(mount);
3020 			XV_COPY(numoutput);
3021 			XV_COPY(type);
3022 #undef XV_COPY
3023 			xvn[n].xv_flag = vp->v_vflag;
3024 
3025 			switch (vp->v_type) {
3026 			case VREG:
3027 			case VDIR:
3028 			case VLNK:
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 		MNT_IUNLOCK(mp);
3055 		mtx_lock(&mountlist_mtx);
3056 		vfs_unbusy(mp);
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 #endif
3070 
3071 /*
3072  * Unmount all filesystems. The list is traversed in reverse order
3073  * of mounting to avoid dependencies.
3074  */
3075 void
3076 vfs_unmountall(void)
3077 {
3078 	struct mount *mp;
3079 	struct thread *td;
3080 	int error;
3081 
3082 	KASSERT(curthread != NULL, ("vfs_unmountall: NULL curthread"));
3083 	td = curthread;
3084 	/*
3085 	 * Since this only runs when rebooting, it is not interlocked.
3086 	 */
3087 	while(!TAILQ_EMPTY(&mountlist)) {
3088 		mp = TAILQ_LAST(&mountlist, mntlist);
3089 		error = dounmount(mp, MNT_FORCE, td);
3090 		if (error) {
3091 			TAILQ_REMOVE(&mountlist, mp, mnt_list);
3092 			/*
3093 			 * XXX: Due to the way in which we mount the root
3094 			 * file system off of devfs, devfs will generate a
3095 			 * "busy" warning when we try to unmount it before
3096 			 * the root.  Don't print a warning as a result in
3097 			 * order to avoid false positive errors that may
3098 			 * cause needless upset.
3099 			 */
3100 			if (strcmp(mp->mnt_vfc->vfc_name, "devfs") != 0) {
3101 				printf("unmount of %s failed (",
3102 				    mp->mnt_stat.f_mntonname);
3103 				if (error == EBUSY)
3104 					printf("BUSY)\n");
3105 				else
3106 					printf("%d)\n", error);
3107 			}
3108 		} else {
3109 			/* The unmount has removed mp from the mountlist */
3110 		}
3111 	}
3112 }
3113 
3114 /*
3115  * perform msync on all vnodes under a mount point
3116  * the mount point must be locked.
3117  */
3118 void
3119 vfs_msync(struct mount *mp, int flags)
3120 {
3121 	struct vnode *vp, *mvp;
3122 	struct vm_object *obj;
3123 
3124 	MNT_ILOCK(mp);
3125 	MNT_VNODE_FOREACH(vp, mp, mvp) {
3126 		VI_LOCK(vp);
3127 		if ((vp->v_iflag & VI_OBJDIRTY) &&
3128 		    (flags == MNT_WAIT || VOP_ISLOCKED(vp) == 0)) {
3129 			MNT_IUNLOCK(mp);
3130 			if (!vget(vp,
3131 			    LK_EXCLUSIVE | LK_RETRY | LK_INTERLOCK,
3132 			    curthread)) {
3133 				if (vp->v_vflag & VV_NOSYNC) {	/* unlinked */
3134 					vput(vp);
3135 					MNT_ILOCK(mp);
3136 					continue;
3137 				}
3138 
3139 				obj = vp->v_object;
3140 				if (obj != NULL) {
3141 					VM_OBJECT_LOCK(obj);
3142 					vm_object_page_clean(obj, 0, 0,
3143 					    flags == MNT_WAIT ?
3144 					    OBJPC_SYNC : OBJPC_NOSYNC);
3145 					VM_OBJECT_UNLOCK(obj);
3146 				}
3147 				vput(vp);
3148 			}
3149 			MNT_ILOCK(mp);
3150 		} else
3151 			VI_UNLOCK(vp);
3152 	}
3153 	MNT_IUNLOCK(mp);
3154 }
3155 
3156 /*
3157  * Mark a vnode as free, putting it up for recycling.
3158  */
3159 static void
3160 vfree(struct vnode *vp)
3161 {
3162 
3163 	CTR1(KTR_VFS, "vfree vp %p", vp);
3164 	ASSERT_VI_LOCKED(vp, "vfree");
3165 	mtx_lock(&vnode_free_list_mtx);
3166 	VNASSERT(vp->v_op != NULL, vp, ("vfree: vnode already reclaimed."));
3167 	VNASSERT((vp->v_iflag & VI_FREE) == 0, vp, ("vnode already free"));
3168 	VNASSERT(VSHOULDFREE(vp), vp, ("vfree: freeing when we shouldn't"));
3169 	VNASSERT((vp->v_iflag & VI_DOOMED) == 0, vp,
3170 	    ("vfree: Freeing doomed vnode"));
3171 	if (vp->v_iflag & VI_AGE) {
3172 		TAILQ_INSERT_HEAD(&vnode_free_list, vp, v_freelist);
3173 	} else {
3174 		TAILQ_INSERT_TAIL(&vnode_free_list, vp, v_freelist);
3175 	}
3176 	freevnodes++;
3177 	vp->v_iflag &= ~VI_AGE;
3178 	vp->v_iflag |= VI_FREE;
3179 	mtx_unlock(&vnode_free_list_mtx);
3180 }
3181 
3182 /*
3183  * Opposite of vfree() - mark a vnode as in use.
3184  */
3185 static void
3186 vbusy(struct vnode *vp)
3187 {
3188 	CTR1(KTR_VFS, "vbusy vp %p", vp);
3189 	ASSERT_VI_LOCKED(vp, "vbusy");
3190 	VNASSERT((vp->v_iflag & VI_FREE) != 0, vp, ("vnode not free"));
3191 	VNASSERT(vp->v_op != NULL, vp, ("vbusy: vnode already reclaimed."));
3192 
3193 	mtx_lock(&vnode_free_list_mtx);
3194 	TAILQ_REMOVE(&vnode_free_list, vp, v_freelist);
3195 	freevnodes--;
3196 	vp->v_iflag &= ~(VI_FREE|VI_AGE);
3197 	mtx_unlock(&vnode_free_list_mtx);
3198 }
3199 
3200 /*
3201  * Initalize per-vnode helper structure to hold poll-related state.
3202  */
3203 void
3204 v_addpollinfo(struct vnode *vp)
3205 {
3206 	struct vpollinfo *vi;
3207 
3208 	vi = uma_zalloc(vnodepoll_zone, M_WAITOK);
3209 	if (vp->v_pollinfo != NULL) {
3210 		uma_zfree(vnodepoll_zone, vi);
3211 		return;
3212 	}
3213 	vp->v_pollinfo = vi;
3214 	mtx_init(&vp->v_pollinfo->vpi_lock, "vnode pollinfo", NULL, MTX_DEF);
3215 	knlist_init(&vp->v_pollinfo->vpi_selinfo.si_note, vp, vfs_knllock,
3216 	    vfs_knlunlock, vfs_knllocked);
3217 }
3218 
3219 /*
3220  * Record a process's interest in events which might happen to
3221  * a vnode.  Because poll uses the historic select-style interface
3222  * internally, this routine serves as both the ``check for any
3223  * pending events'' and the ``record my interest in future events''
3224  * functions.  (These are done together, while the lock is held,
3225  * to avoid race conditions.)
3226  */
3227 int
3228 vn_pollrecord(struct vnode *vp, struct thread *td, int events)
3229 {
3230 
3231 	if (vp->v_pollinfo == NULL)
3232 		v_addpollinfo(vp);
3233 	mtx_lock(&vp->v_pollinfo->vpi_lock);
3234 	if (vp->v_pollinfo->vpi_revents & events) {
3235 		/*
3236 		 * This leaves events we are not interested
3237 		 * in available for the other process which
3238 		 * which presumably had requested them
3239 		 * (otherwise they would never have been
3240 		 * recorded).
3241 		 */
3242 		events &= vp->v_pollinfo->vpi_revents;
3243 		vp->v_pollinfo->vpi_revents &= ~events;
3244 
3245 		mtx_unlock(&vp->v_pollinfo->vpi_lock);
3246 		return events;
3247 	}
3248 	vp->v_pollinfo->vpi_events |= events;
3249 	selrecord(td, &vp->v_pollinfo->vpi_selinfo);
3250 	mtx_unlock(&vp->v_pollinfo->vpi_lock);
3251 	return 0;
3252 }
3253 
3254 /*
3255  * Routine to create and manage a filesystem syncer vnode.
3256  */
3257 #define sync_close ((int (*)(struct  vop_close_args *))nullop)
3258 static int	sync_fsync(struct  vop_fsync_args *);
3259 static int	sync_inactive(struct  vop_inactive_args *);
3260 static int	sync_reclaim(struct  vop_reclaim_args *);
3261 
3262 static struct vop_vector sync_vnodeops = {
3263 	.vop_bypass =	VOP_EOPNOTSUPP,
3264 	.vop_close =	sync_close,		/* close */
3265 	.vop_fsync =	sync_fsync,		/* fsync */
3266 	.vop_inactive =	sync_inactive,	/* inactive */
3267 	.vop_reclaim =	sync_reclaim,	/* reclaim */
3268 	.vop_lock1 =	vop_stdlock,	/* lock */
3269 	.vop_unlock =	vop_stdunlock,	/* unlock */
3270 	.vop_islocked =	vop_stdislocked,	/* islocked */
3271 };
3272 
3273 /*
3274  * Create a new filesystem syncer vnode for the specified mount point.
3275  */
3276 int
3277 vfs_allocate_syncvnode(struct mount *mp)
3278 {
3279 	struct vnode *vp;
3280 	struct bufobj *bo;
3281 	static long start, incr, next;
3282 	int error;
3283 
3284 	/* Allocate a new vnode */
3285 	if ((error = getnewvnode("syncer", mp, &sync_vnodeops, &vp)) != 0) {
3286 		mp->mnt_syncer = NULL;
3287 		return (error);
3288 	}
3289 	vp->v_type = VNON;
3290 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
3291 	vp->v_vflag |= VV_FORCEINSMQ;
3292 	error = insmntque(vp, mp);
3293 	if (error != 0)
3294 		panic("vfs_allocate_syncvnode: insmntque failed");
3295 	vp->v_vflag &= ~VV_FORCEINSMQ;
3296 	VOP_UNLOCK(vp, 0);
3297 	/*
3298 	 * Place the vnode onto the syncer worklist. We attempt to
3299 	 * scatter them about on the list so that they will go off
3300 	 * at evenly distributed times even if all the filesystems
3301 	 * are mounted at once.
3302 	 */
3303 	next += incr;
3304 	if (next == 0 || next > syncer_maxdelay) {
3305 		start /= 2;
3306 		incr /= 2;
3307 		if (start == 0) {
3308 			start = syncer_maxdelay / 2;
3309 			incr = syncer_maxdelay;
3310 		}
3311 		next = start;
3312 	}
3313 	bo = &vp->v_bufobj;
3314 	BO_LOCK(bo);
3315 	vn_syncer_add_to_worklist(bo, syncdelay > 0 ? next % syncdelay : 0);
3316 	/* XXX - vn_syncer_add_to_worklist() also grabs and drops sync_mtx. */
3317 	mtx_lock(&sync_mtx);
3318 	sync_vnode_count++;
3319 	mtx_unlock(&sync_mtx);
3320 	BO_UNLOCK(bo);
3321 	mp->mnt_syncer = vp;
3322 	return (0);
3323 }
3324 
3325 /*
3326  * Do a lazy sync of the filesystem.
3327  */
3328 static int
3329 sync_fsync(struct vop_fsync_args *ap)
3330 {
3331 	struct vnode *syncvp = ap->a_vp;
3332 	struct mount *mp = syncvp->v_mount;
3333 	int error;
3334 	struct bufobj *bo;
3335 
3336 	/*
3337 	 * We only need to do something if this is a lazy evaluation.
3338 	 */
3339 	if (ap->a_waitfor != MNT_LAZY)
3340 		return (0);
3341 
3342 	/*
3343 	 * Move ourselves to the back of the sync list.
3344 	 */
3345 	bo = &syncvp->v_bufobj;
3346 	BO_LOCK(bo);
3347 	vn_syncer_add_to_worklist(bo, syncdelay);
3348 	BO_UNLOCK(bo);
3349 
3350 	/*
3351 	 * Walk the list of vnodes pushing all that are dirty and
3352 	 * not already on the sync list.
3353 	 */
3354 	mtx_lock(&mountlist_mtx);
3355 	if (vfs_busy(mp, LK_EXCLUSIVE | LK_NOWAIT, &mountlist_mtx) != 0) {
3356 		mtx_unlock(&mountlist_mtx);
3357 		return (0);
3358 	}
3359 	if (vn_start_write(NULL, &mp, V_NOWAIT) != 0) {
3360 		vfs_unbusy(mp);
3361 		return (0);
3362 	}
3363 	MNT_ILOCK(mp);
3364 	mp->mnt_noasync++;
3365 	mp->mnt_kern_flag &= ~MNTK_ASYNC;
3366 	MNT_IUNLOCK(mp);
3367 	vfs_msync(mp, MNT_NOWAIT);
3368 	error = VFS_SYNC(mp, MNT_LAZY, ap->a_td);
3369 	MNT_ILOCK(mp);
3370 	mp->mnt_noasync--;
3371 	if ((mp->mnt_flag & MNT_ASYNC) != 0 && mp->mnt_noasync == 0)
3372 		mp->mnt_kern_flag |= MNTK_ASYNC;
3373 	MNT_IUNLOCK(mp);
3374 	vn_finished_write(mp);
3375 	vfs_unbusy(mp);
3376 	return (error);
3377 }
3378 
3379 /*
3380  * The syncer vnode is no referenced.
3381  */
3382 static int
3383 sync_inactive(struct vop_inactive_args *ap)
3384 {
3385 
3386 	vgone(ap->a_vp);
3387 	return (0);
3388 }
3389 
3390 /*
3391  * The syncer vnode is no longer needed and is being decommissioned.
3392  *
3393  * Modifications to the worklist must be protected by sync_mtx.
3394  */
3395 static int
3396 sync_reclaim(struct vop_reclaim_args *ap)
3397 {
3398 	struct vnode *vp = ap->a_vp;
3399 	struct bufobj *bo;
3400 
3401 	bo = &vp->v_bufobj;
3402 	BO_LOCK(bo);
3403 	vp->v_mount->mnt_syncer = NULL;
3404 	if (bo->bo_flag & BO_ONWORKLST) {
3405 		mtx_lock(&sync_mtx);
3406 		LIST_REMOVE(bo, bo_synclist);
3407 		syncer_worklist_len--;
3408 		sync_vnode_count--;
3409 		mtx_unlock(&sync_mtx);
3410 		bo->bo_flag &= ~BO_ONWORKLST;
3411 	}
3412 	BO_UNLOCK(bo);
3413 
3414 	return (0);
3415 }
3416 
3417 /*
3418  * Check if vnode represents a disk device
3419  */
3420 int
3421 vn_isdisk(struct vnode *vp, int *errp)
3422 {
3423 	int error;
3424 
3425 	error = 0;
3426 	dev_lock();
3427 	if (vp->v_type != VCHR)
3428 		error = ENOTBLK;
3429 	else if (vp->v_rdev == NULL)
3430 		error = ENXIO;
3431 	else if (vp->v_rdev->si_devsw == NULL)
3432 		error = ENXIO;
3433 	else if (!(vp->v_rdev->si_devsw->d_flags & D_DISK))
3434 		error = ENOTBLK;
3435 	dev_unlock();
3436 	if (errp != NULL)
3437 		*errp = error;
3438 	return (error == 0);
3439 }
3440 
3441 /*
3442  * Common filesystem object access control check routine.  Accepts a
3443  * vnode's type, "mode", uid and gid, requested access mode, credentials,
3444  * and optional call-by-reference privused argument allowing vaccess()
3445  * to indicate to the caller whether privilege was used to satisfy the
3446  * request (obsoleted).  Returns 0 on success, or an errno on failure.
3447  *
3448  * The ifdef'd CAPABILITIES version is here for reference, but is not
3449  * actually used.
3450  */
3451 int
3452 vaccess(enum vtype type, mode_t file_mode, uid_t file_uid, gid_t file_gid,
3453     mode_t acc_mode, struct ucred *cred, int *privused)
3454 {
3455 	mode_t dac_granted;
3456 	mode_t priv_granted;
3457 
3458 	/*
3459 	 * Look for a normal, non-privileged way to access the file/directory
3460 	 * as requested.  If it exists, go with that.
3461 	 */
3462 
3463 	if (privused != NULL)
3464 		*privused = 0;
3465 
3466 	dac_granted = 0;
3467 
3468 	/* Check the owner. */
3469 	if (cred->cr_uid == file_uid) {
3470 		dac_granted |= VADMIN;
3471 		if (file_mode & S_IXUSR)
3472 			dac_granted |= VEXEC;
3473 		if (file_mode & S_IRUSR)
3474 			dac_granted |= VREAD;
3475 		if (file_mode & S_IWUSR)
3476 			dac_granted |= (VWRITE | VAPPEND);
3477 
3478 		if ((acc_mode & dac_granted) == acc_mode)
3479 			return (0);
3480 
3481 		goto privcheck;
3482 	}
3483 
3484 	/* Otherwise, check the groups (first match) */
3485 	if (groupmember(file_gid, cred)) {
3486 		if (file_mode & S_IXGRP)
3487 			dac_granted |= VEXEC;
3488 		if (file_mode & S_IRGRP)
3489 			dac_granted |= VREAD;
3490 		if (file_mode & S_IWGRP)
3491 			dac_granted |= (VWRITE | VAPPEND);
3492 
3493 		if ((acc_mode & dac_granted) == acc_mode)
3494 			return (0);
3495 
3496 		goto privcheck;
3497 	}
3498 
3499 	/* Otherwise, check everyone else. */
3500 	if (file_mode & S_IXOTH)
3501 		dac_granted |= VEXEC;
3502 	if (file_mode & S_IROTH)
3503 		dac_granted |= VREAD;
3504 	if (file_mode & S_IWOTH)
3505 		dac_granted |= (VWRITE | VAPPEND);
3506 	if ((acc_mode & dac_granted) == acc_mode)
3507 		return (0);
3508 
3509 privcheck:
3510 	/*
3511 	 * Build a privilege mask to determine if the set of privileges
3512 	 * satisfies the requirements when combined with the granted mask
3513 	 * from above.  For each privilege, if the privilege is required,
3514 	 * bitwise or the request type onto the priv_granted mask.
3515 	 */
3516 	priv_granted = 0;
3517 
3518 	if (type == VDIR) {
3519 		/*
3520 		 * For directories, use PRIV_VFS_LOOKUP to satisfy VEXEC
3521 		 * requests, instead of PRIV_VFS_EXEC.
3522 		 */
3523 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3524 		    !priv_check_cred(cred, PRIV_VFS_LOOKUP, 0))
3525 			priv_granted |= VEXEC;
3526 	} else {
3527 		if ((acc_mode & VEXEC) && ((dac_granted & VEXEC) == 0) &&
3528 		    !priv_check_cred(cred, PRIV_VFS_EXEC, 0))
3529 			priv_granted |= VEXEC;
3530 	}
3531 
3532 	if ((acc_mode & VREAD) && ((dac_granted & VREAD) == 0) &&
3533 	    !priv_check_cred(cred, PRIV_VFS_READ, 0))
3534 		priv_granted |= VREAD;
3535 
3536 	if ((acc_mode & VWRITE) && ((dac_granted & VWRITE) == 0) &&
3537 	    !priv_check_cred(cred, PRIV_VFS_WRITE, 0))
3538 		priv_granted |= (VWRITE | VAPPEND);
3539 
3540 	if ((acc_mode & VADMIN) && ((dac_granted & VADMIN) == 0) &&
3541 	    !priv_check_cred(cred, PRIV_VFS_ADMIN, 0))
3542 		priv_granted |= VADMIN;
3543 
3544 	if ((acc_mode & (priv_granted | dac_granted)) == acc_mode) {
3545 		/* XXX audit: privilege used */
3546 		if (privused != NULL)
3547 			*privused = 1;
3548 		return (0);
3549 	}
3550 
3551 	return ((acc_mode & VADMIN) ? EPERM : EACCES);
3552 }
3553 
3554 /*
3555  * Credential check based on process requesting service, and per-attribute
3556  * permissions.
3557  */
3558 int
3559 extattr_check_cred(struct vnode *vp, int attrnamespace, struct ucred *cred,
3560     struct thread *td, int access)
3561 {
3562 
3563 	/*
3564 	 * Kernel-invoked always succeeds.
3565 	 */
3566 	if (cred == NOCRED)
3567 		return (0);
3568 
3569 	/*
3570 	 * Do not allow privileged processes in jail to directly manipulate
3571 	 * system attributes.
3572 	 */
3573 	switch (attrnamespace) {
3574 	case EXTATTR_NAMESPACE_SYSTEM:
3575 		/* Potentially should be: return (EPERM); */
3576 		return (priv_check_cred(cred, PRIV_VFS_EXTATTR_SYSTEM, 0));
3577 	case EXTATTR_NAMESPACE_USER:
3578 		return (VOP_ACCESS(vp, access, cred, td));
3579 	default:
3580 		return (EPERM);
3581 	}
3582 }
3583 
3584 #ifdef DEBUG_VFS_LOCKS
3585 /*
3586  * This only exists to supress warnings from unlocked specfs accesses.  It is
3587  * no longer ok to have an unlocked VFS.
3588  */
3589 #define	IGNORE_LOCK(vp) (panicstr != NULL || (vp) == NULL ||		\
3590 	(vp)->v_type == VCHR ||	(vp)->v_type == VBAD)
3591 
3592 int vfs_badlock_ddb = 1;	/* Drop into debugger on violation. */
3593 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_ddb, CTLFLAG_RW, &vfs_badlock_ddb, 0, "");
3594 
3595 int vfs_badlock_mutex = 1;	/* Check for interlock across VOPs. */
3596 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_mutex, CTLFLAG_RW, &vfs_badlock_mutex, 0, "");
3597 
3598 int vfs_badlock_print = 1;	/* Print lock violations. */
3599 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_print, CTLFLAG_RW, &vfs_badlock_print, 0, "");
3600 
3601 #ifdef KDB
3602 int vfs_badlock_backtrace = 1;	/* Print backtrace at lock violations. */
3603 SYSCTL_INT(_debug, OID_AUTO, vfs_badlock_backtrace, CTLFLAG_RW, &vfs_badlock_backtrace, 0, "");
3604 #endif
3605 
3606 static void
3607 vfs_badlock(const char *msg, const char *str, struct vnode *vp)
3608 {
3609 
3610 #ifdef KDB
3611 	if (vfs_badlock_backtrace)
3612 		kdb_backtrace();
3613 #endif
3614 	if (vfs_badlock_print)
3615 		printf("%s: %p %s\n", str, (void *)vp, msg);
3616 	if (vfs_badlock_ddb)
3617 		kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3618 }
3619 
3620 void
3621 assert_vi_locked(struct vnode *vp, const char *str)
3622 {
3623 
3624 	if (vfs_badlock_mutex && !mtx_owned(VI_MTX(vp)))
3625 		vfs_badlock("interlock is not locked but should be", str, vp);
3626 }
3627 
3628 void
3629 assert_vi_unlocked(struct vnode *vp, const char *str)
3630 {
3631 
3632 	if (vfs_badlock_mutex && mtx_owned(VI_MTX(vp)))
3633 		vfs_badlock("interlock is locked but should not be", str, vp);
3634 }
3635 
3636 void
3637 assert_vop_locked(struct vnode *vp, const char *str)
3638 {
3639 
3640 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == 0)
3641 		vfs_badlock("is not locked but should be", str, vp);
3642 }
3643 
3644 void
3645 assert_vop_unlocked(struct vnode *vp, const char *str)
3646 {
3647 
3648 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) == LK_EXCLUSIVE)
3649 		vfs_badlock("is locked but should not be", str, vp);
3650 }
3651 
3652 void
3653 assert_vop_elocked(struct vnode *vp, const char *str)
3654 {
3655 
3656 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLUSIVE)
3657 		vfs_badlock("is not exclusive locked but should be", str, vp);
3658 }
3659 
3660 #if 0
3661 void
3662 assert_vop_elocked_other(struct vnode *vp, const char *str)
3663 {
3664 
3665 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_EXCLOTHER)
3666 		vfs_badlock("is not exclusive locked by another thread",
3667 		    str, vp);
3668 }
3669 
3670 void
3671 assert_vop_slocked(struct vnode *vp, const char *str)
3672 {
3673 
3674 	if (!IGNORE_LOCK(vp) && VOP_ISLOCKED(vp) != LK_SHARED)
3675 		vfs_badlock("is not locked shared but should be", str, vp);
3676 }
3677 #endif /* 0 */
3678 #endif /* DEBUG_VFS_LOCKS */
3679 
3680 void
3681 vop_rename_pre(void *ap)
3682 {
3683 	struct vop_rename_args *a = ap;
3684 
3685 #ifdef DEBUG_VFS_LOCKS
3686 	if (a->a_tvp)
3687 		ASSERT_VI_UNLOCKED(a->a_tvp, "VOP_RENAME");
3688 	ASSERT_VI_UNLOCKED(a->a_tdvp, "VOP_RENAME");
3689 	ASSERT_VI_UNLOCKED(a->a_fvp, "VOP_RENAME");
3690 	ASSERT_VI_UNLOCKED(a->a_fdvp, "VOP_RENAME");
3691 
3692 	/* Check the source (from). */
3693 	if (a->a_tdvp != a->a_fdvp && a->a_tvp != a->a_fdvp)
3694 		ASSERT_VOP_UNLOCKED(a->a_fdvp, "vop_rename: fdvp locked");
3695 	if (a->a_tvp != a->a_fvp)
3696 		ASSERT_VOP_UNLOCKED(a->a_fvp, "vop_rename: fvp locked");
3697 
3698 	/* Check the target. */
3699 	if (a->a_tvp)
3700 		ASSERT_VOP_LOCKED(a->a_tvp, "vop_rename: tvp not locked");
3701 	ASSERT_VOP_LOCKED(a->a_tdvp, "vop_rename: tdvp not locked");
3702 #endif
3703 	if (a->a_tdvp != a->a_fdvp)
3704 		vhold(a->a_fdvp);
3705 	if (a->a_tvp != a->a_fvp)
3706 		vhold(a->a_fvp);
3707 	vhold(a->a_tdvp);
3708 	if (a->a_tvp)
3709 		vhold(a->a_tvp);
3710 }
3711 
3712 void
3713 vop_strategy_pre(void *ap)
3714 {
3715 #ifdef DEBUG_VFS_LOCKS
3716 	struct vop_strategy_args *a;
3717 	struct buf *bp;
3718 
3719 	a = ap;
3720 	bp = a->a_bp;
3721 
3722 	/*
3723 	 * Cluster ops lock their component buffers but not the IO container.
3724 	 */
3725 	if ((bp->b_flags & B_CLUSTER) != 0)
3726 		return;
3727 
3728 	if (!BUF_ISLOCKED(bp)) {
3729 		if (vfs_badlock_print)
3730 			printf(
3731 			    "VOP_STRATEGY: bp is not locked but should be\n");
3732 		if (vfs_badlock_ddb)
3733 			kdb_enter(KDB_WHY_VFSLOCK, "lock violation");
3734 	}
3735 #endif
3736 }
3737 
3738 void
3739 vop_lookup_pre(void *ap)
3740 {
3741 #ifdef DEBUG_VFS_LOCKS
3742 	struct vop_lookup_args *a;
3743 	struct vnode *dvp;
3744 
3745 	a = ap;
3746 	dvp = a->a_dvp;
3747 	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3748 	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3749 #endif
3750 }
3751 
3752 void
3753 vop_lookup_post(void *ap, int rc)
3754 {
3755 #ifdef DEBUG_VFS_LOCKS
3756 	struct vop_lookup_args *a;
3757 	struct vnode *dvp;
3758 	struct vnode *vp;
3759 
3760 	a = ap;
3761 	dvp = a->a_dvp;
3762 	vp = *(a->a_vpp);
3763 
3764 	ASSERT_VI_UNLOCKED(dvp, "VOP_LOOKUP");
3765 	ASSERT_VOP_LOCKED(dvp, "VOP_LOOKUP");
3766 
3767 	if (!rc)
3768 		ASSERT_VOP_LOCKED(vp, "VOP_LOOKUP (child)");
3769 #endif
3770 }
3771 
3772 void
3773 vop_lock_pre(void *ap)
3774 {
3775 #ifdef DEBUG_VFS_LOCKS
3776 	struct vop_lock1_args *a = ap;
3777 
3778 	if ((a->a_flags & LK_INTERLOCK) == 0)
3779 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3780 	else
3781 		ASSERT_VI_LOCKED(a->a_vp, "VOP_LOCK");
3782 #endif
3783 }
3784 
3785 void
3786 vop_lock_post(void *ap, int rc)
3787 {
3788 #ifdef DEBUG_VFS_LOCKS
3789 	struct vop_lock1_args *a = ap;
3790 
3791 	ASSERT_VI_UNLOCKED(a->a_vp, "VOP_LOCK");
3792 	if (rc == 0)
3793 		ASSERT_VOP_LOCKED(a->a_vp, "VOP_LOCK");
3794 #endif
3795 }
3796 
3797 void
3798 vop_unlock_pre(void *ap)
3799 {
3800 #ifdef DEBUG_VFS_LOCKS
3801 	struct vop_unlock_args *a = ap;
3802 
3803 	if (a->a_flags & LK_INTERLOCK)
3804 		ASSERT_VI_LOCKED(a->a_vp, "VOP_UNLOCK");
3805 	ASSERT_VOP_LOCKED(a->a_vp, "VOP_UNLOCK");
3806 #endif
3807 }
3808 
3809 void
3810 vop_unlock_post(void *ap, int rc)
3811 {
3812 #ifdef DEBUG_VFS_LOCKS
3813 	struct vop_unlock_args *a = ap;
3814 
3815 	if (a->a_flags & LK_INTERLOCK)
3816 		ASSERT_VI_UNLOCKED(a->a_vp, "VOP_UNLOCK");
3817 #endif
3818 }
3819 
3820 void
3821 vop_create_post(void *ap, int rc)
3822 {
3823 	struct vop_create_args *a = ap;
3824 
3825 	if (!rc)
3826 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3827 }
3828 
3829 void
3830 vop_link_post(void *ap, int rc)
3831 {
3832 	struct vop_link_args *a = ap;
3833 
3834 	if (!rc) {
3835 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_LINK);
3836 		VFS_KNOTE_LOCKED(a->a_tdvp, NOTE_WRITE);
3837 	}
3838 }
3839 
3840 void
3841 vop_mkdir_post(void *ap, int rc)
3842 {
3843 	struct vop_mkdir_args *a = ap;
3844 
3845 	if (!rc)
3846 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3847 }
3848 
3849 void
3850 vop_mknod_post(void *ap, int rc)
3851 {
3852 	struct vop_mknod_args *a = ap;
3853 
3854 	if (!rc)
3855 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3856 }
3857 
3858 void
3859 vop_remove_post(void *ap, int rc)
3860 {
3861 	struct vop_remove_args *a = ap;
3862 
3863 	if (!rc) {
3864 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3865 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3866 	}
3867 }
3868 
3869 void
3870 vop_rename_post(void *ap, int rc)
3871 {
3872 	struct vop_rename_args *a = ap;
3873 
3874 	if (!rc) {
3875 		VFS_KNOTE_UNLOCKED(a->a_fdvp, NOTE_WRITE);
3876 		VFS_KNOTE_UNLOCKED(a->a_tdvp, NOTE_WRITE);
3877 		VFS_KNOTE_UNLOCKED(a->a_fvp, NOTE_RENAME);
3878 		if (a->a_tvp)
3879 			VFS_KNOTE_UNLOCKED(a->a_tvp, NOTE_DELETE);
3880 	}
3881 	if (a->a_tdvp != a->a_fdvp)
3882 		vdrop(a->a_fdvp);
3883 	if (a->a_tvp != a->a_fvp)
3884 		vdrop(a->a_fvp);
3885 	vdrop(a->a_tdvp);
3886 	if (a->a_tvp)
3887 		vdrop(a->a_tvp);
3888 }
3889 
3890 void
3891 vop_rmdir_post(void *ap, int rc)
3892 {
3893 	struct vop_rmdir_args *a = ap;
3894 
3895 	if (!rc) {
3896 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE | NOTE_LINK);
3897 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_DELETE);
3898 	}
3899 }
3900 
3901 void
3902 vop_setattr_post(void *ap, int rc)
3903 {
3904 	struct vop_setattr_args *a = ap;
3905 
3906 	if (!rc)
3907 		VFS_KNOTE_LOCKED(a->a_vp, NOTE_ATTRIB);
3908 }
3909 
3910 void
3911 vop_symlink_post(void *ap, int rc)
3912 {
3913 	struct vop_symlink_args *a = ap;
3914 
3915 	if (!rc)
3916 		VFS_KNOTE_LOCKED(a->a_dvp, NOTE_WRITE);
3917 }
3918 
3919 static struct knlist fs_knlist;
3920 
3921 static void
3922 vfs_event_init(void *arg)
3923 {
3924 	knlist_init(&fs_knlist, NULL, NULL, NULL, NULL);
3925 }
3926 /* XXX - correct order? */
3927 SYSINIT(vfs_knlist, SI_SUB_VFS, SI_ORDER_ANY, vfs_event_init, NULL);
3928 
3929 void
3930 vfs_event_signal(fsid_t *fsid, u_int32_t event, intptr_t data __unused)
3931 {
3932 
3933 	KNOTE_UNLOCKED(&fs_knlist, event);
3934 }
3935 
3936 static int	filt_fsattach(struct knote *kn);
3937 static void	filt_fsdetach(struct knote *kn);
3938 static int	filt_fsevent(struct knote *kn, long hint);
3939 
3940 struct filterops fs_filtops =
3941 	{ 0, filt_fsattach, filt_fsdetach, filt_fsevent };
3942 
3943 static int
3944 filt_fsattach(struct knote *kn)
3945 {
3946 
3947 	kn->kn_flags |= EV_CLEAR;
3948 	knlist_add(&fs_knlist, kn, 0);
3949 	return (0);
3950 }
3951 
3952 static void
3953 filt_fsdetach(struct knote *kn)
3954 {
3955 
3956 	knlist_remove(&fs_knlist, kn, 0);
3957 }
3958 
3959 static int
3960 filt_fsevent(struct knote *kn, long hint)
3961 {
3962 
3963 	kn->kn_fflags |= hint;
3964 	return (kn->kn_fflags != 0);
3965 }
3966 
3967 static int
3968 sysctl_vfs_ctl(SYSCTL_HANDLER_ARGS)
3969 {
3970 	struct vfsidctl vc;
3971 	int error;
3972 	struct mount *mp;
3973 
3974 	error = SYSCTL_IN(req, &vc, sizeof(vc));
3975 	if (error)
3976 		return (error);
3977 	if (vc.vc_vers != VFS_CTL_VERS1)
3978 		return (EINVAL);
3979 	mp = vfs_getvfs(&vc.vc_fsid);
3980 	if (mp == NULL)
3981 		return (ENOENT);
3982 	/* ensure that a specific sysctl goes to the right filesystem. */
3983 	if (strcmp(vc.vc_fstypename, "*") != 0 &&
3984 	    strcmp(vc.vc_fstypename, mp->mnt_vfc->vfc_name) != 0) {
3985 		vfs_rel(mp);
3986 		return (EINVAL);
3987 	}
3988 	VCTLTOREQ(&vc, req);
3989 	error = VFS_SYSCTL(mp, vc.vc_op, req);
3990 	vfs_rel(mp);
3991 	return (error);
3992 }
3993 
3994 SYSCTL_PROC(_vfs, OID_AUTO, ctl, CTLFLAG_WR, NULL, 0, sysctl_vfs_ctl, "",
3995     "Sysctl by fsid");
3996 
3997 /*
3998  * Function to initialize a va_filerev field sensibly.
3999  * XXX: Wouldn't a random number make a lot more sense ??
4000  */
4001 u_quad_t
4002 init_va_filerev(void)
4003 {
4004 	struct bintime bt;
4005 
4006 	getbinuptime(&bt);
4007 	return (((u_quad_t)bt.sec << 32LL) | (bt.frac >> 32LL));
4008 }
4009 
4010 static int	filt_vfsread(struct knote *kn, long hint);
4011 static int	filt_vfswrite(struct knote *kn, long hint);
4012 static int	filt_vfsvnode(struct knote *kn, long hint);
4013 static void	filt_vfsdetach(struct knote *kn);
4014 static struct filterops vfsread_filtops =
4015 	{ 1, NULL, filt_vfsdetach, filt_vfsread };
4016 static struct filterops vfswrite_filtops =
4017 	{ 1, NULL, filt_vfsdetach, filt_vfswrite };
4018 static struct filterops vfsvnode_filtops =
4019 	{ 1, NULL, filt_vfsdetach, filt_vfsvnode };
4020 
4021 static void
4022 vfs_knllock(void *arg)
4023 {
4024 	struct vnode *vp = arg;
4025 
4026 	vn_lock(vp, LK_EXCLUSIVE | LK_RETRY);
4027 }
4028 
4029 static void
4030 vfs_knlunlock(void *arg)
4031 {
4032 	struct vnode *vp = arg;
4033 
4034 	VOP_UNLOCK(vp, 0);
4035 }
4036 
4037 static int
4038 vfs_knllocked(void *arg)
4039 {
4040 	struct vnode *vp = arg;
4041 
4042 	return (VOP_ISLOCKED(vp) == LK_EXCLUSIVE);
4043 }
4044 
4045 int
4046 vfs_kqfilter(struct vop_kqfilter_args *ap)
4047 {
4048 	struct vnode *vp = ap->a_vp;
4049 	struct knote *kn = ap->a_kn;
4050 	struct knlist *knl;
4051 
4052 	switch (kn->kn_filter) {
4053 	case EVFILT_READ:
4054 		kn->kn_fop = &vfsread_filtops;
4055 		break;
4056 	case EVFILT_WRITE:
4057 		kn->kn_fop = &vfswrite_filtops;
4058 		break;
4059 	case EVFILT_VNODE:
4060 		kn->kn_fop = &vfsvnode_filtops;
4061 		break;
4062 	default:
4063 		return (EINVAL);
4064 	}
4065 
4066 	kn->kn_hook = (caddr_t)vp;
4067 
4068 	if (vp->v_pollinfo == NULL)
4069 		v_addpollinfo(vp);
4070 	if (vp->v_pollinfo == NULL)
4071 		return (ENOMEM);
4072 	knl = &vp->v_pollinfo->vpi_selinfo.si_note;
4073 	knlist_add(knl, kn, 0);
4074 
4075 	return (0);
4076 }
4077 
4078 /*
4079  * Detach knote from vnode
4080  */
4081 static void
4082 filt_vfsdetach(struct knote *kn)
4083 {
4084 	struct vnode *vp = (struct vnode *)kn->kn_hook;
4085 
4086 	KASSERT(vp->v_pollinfo != NULL, ("Missing v_pollinfo"));
4087 	knlist_remove(&vp->v_pollinfo->vpi_selinfo.si_note, kn, 0);
4088 }
4089 
4090 /*ARGSUSED*/
4091 static int
4092 filt_vfsread(struct knote *kn, long hint)
4093 {
4094 	struct vnode *vp = (struct vnode *)kn->kn_hook;
4095 	struct vattr va;
4096 
4097 	/*
4098 	 * filesystem is gone, so set the EOF flag and schedule
4099 	 * the knote for deletion.
4100 	 */
4101 	if (hint == NOTE_REVOKE) {
4102 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4103 		return (1);
4104 	}
4105 
4106 	if (VOP_GETATTR(vp, &va, curthread->td_ucred))
4107 		return (0);
4108 
4109 	kn->kn_data = va.va_size - kn->kn_fp->f_offset;
4110 	return (kn->kn_data != 0);
4111 }
4112 
4113 /*ARGSUSED*/
4114 static int
4115 filt_vfswrite(struct knote *kn, long hint)
4116 {
4117 	/*
4118 	 * filesystem is gone, so set the EOF flag and schedule
4119 	 * the knote for deletion.
4120 	 */
4121 	if (hint == NOTE_REVOKE)
4122 		kn->kn_flags |= (EV_EOF | EV_ONESHOT);
4123 
4124 	kn->kn_data = 0;
4125 	return (1);
4126 }
4127 
4128 static int
4129 filt_vfsvnode(struct knote *kn, long hint)
4130 {
4131 	if (kn->kn_sfflags & hint)
4132 		kn->kn_fflags |= hint;
4133 	if (hint == NOTE_REVOKE) {
4134 		kn->kn_flags |= EV_EOF;
4135 		return (1);
4136 	}
4137 	return (kn->kn_fflags != 0);
4138 }
4139 
4140 int
4141 vfs_read_dirent(struct vop_readdir_args *ap, struct dirent *dp, off_t off)
4142 {
4143 	int error;
4144 
4145 	if (dp->d_reclen > ap->a_uio->uio_resid)
4146 		return (ENAMETOOLONG);
4147 	error = uiomove(dp, dp->d_reclen, ap->a_uio);
4148 	if (error) {
4149 		if (ap->a_ncookies != NULL) {
4150 			if (ap->a_cookies != NULL)
4151 				free(ap->a_cookies, M_TEMP);
4152 			ap->a_cookies = NULL;
4153 			*ap->a_ncookies = 0;
4154 		}
4155 		return (error);
4156 	}
4157 	if (ap->a_ncookies == NULL)
4158 		return (0);
4159 
4160 	KASSERT(ap->a_cookies,
4161 	    ("NULL ap->a_cookies value with non-NULL ap->a_ncookies!"));
4162 
4163 	*ap->a_cookies = realloc(*ap->a_cookies,
4164 	    (*ap->a_ncookies + 1) * sizeof(u_long), M_TEMP, M_WAITOK | M_ZERO);
4165 	(*ap->a_cookies)[*ap->a_ncookies] = off;
4166 	return (0);
4167 }
4168 
4169 /*
4170  * Mark for update the access time of the file if the filesystem
4171  * supports VA_MARK_ATIME.  This functionality is used by execve
4172  * and mmap, so we want to avoid the synchronous I/O implied by
4173  * directly setting va_atime for the sake of efficiency.
4174  */
4175 void
4176 vfs_mark_atime(struct vnode *vp, struct ucred *cred)
4177 {
4178 	struct vattr atimeattr;
4179 
4180 	if ((vp->v_mount->mnt_flag & (MNT_NOATIME | MNT_RDONLY)) == 0) {
4181 		VATTR_NULL(&atimeattr);
4182 		atimeattr.va_vaflags |= VA_MARK_ATIME;
4183 		(void)VOP_SETATTR(vp, &atimeattr, cred);
4184 	}
4185 }
4186